import json

from django.test import RequestFactory, TestCase
from django.views.generic.list import ListView
from model_bakery import baker

import teramap

from .app.models import Location


class GeoJSONViewTest(TestCase):
    def setUp(self):
        # Every test needs access to the request factory.
        self.factory = RequestFactory()
        baker.make(Location, name="puntje", geom="POINT(4 2)")
        baker.make(Location, name="lijntje", geom="LINESTRING(30 10, 10 30, 40 40)")

    def test_view(self):
        class GeoJSON(teramap.GeoJSON):
            properties = {"id": "id", "name": "name"}

        class View(teramap.GeoJSONView, ListView):
            GeoJSONClass = GeoJSON
            model = Location

            def get_ordering(self):
                return "name"

        view = View.as_view()

        response = view(self.factory.get("location.geojson"))
        data = json.loads(response.content.decode("utf-8"))

        self.assertEqual(data["type"], "FeatureCollection")
        self.assertEqual(
            [(feature["properties"]["name"], feature["geometry"]["coordinates"]) for feature in data["features"]],
            [("lijntje", [[30, 10], [10, 30], [40, 40]]), ("puntje", [4, 2])],
        )
