"""
Author: Michel Peltriaux
Organization: Struktur- und Genehmigungsdirektion Nord, Rhineland-Palatinate, Germany
Contact: michel.peltriaux@sgdnord.rlp.de
Created on: 28.01.22

"""

import json

from django.contrib.gis import geos
from django.urls import reverse

from api.tests.v1.share.test_api_sharing import BaseAPIV1TestCase
from konova.sub_settings.lanis_settings import DEFAULT_SRID_RLP


class APIV1UpdateTestCase(BaseAPIV1TestCase):
    @classmethod
    def setUpTestData(cls):
        super().setUpTestData()

    def _run_update_request(self, url, data):
        data = json.dumps(data)
        response = self.client.put(
            url,
            data=data,
            content_type="application/json",
            **self.header_data
        )
        return response

    def _test_update_object(self, url, put_body):
        """ Tests the API update of a data object.

        Put body data stored in a local json file

        Args:
            url (str): The api creation url
            put_body (dict): The put body content as dict

        Returns:

        """
        response = self._run_update_request(url, put_body)
        self.assertEqual(response.status_code, 200, msg=response.content)
        content = json.loads(response.content)
        self.assertIsNotNone(content.get("id", None), msg=response.content)

    def test_update_intervention(self):
        """ Tests api update

        Returns:

        """
        self.intervention.share_with_user(self.superuser)
        modified_on = self.intervention.modified
        url = reverse("api:v1:intervention", args=(str(self.intervention.id),))
        json_file_path = "api/tests/v1/update/intervention_update_put_body.json"
        with open(json_file_path) as json_file:
            put_body = json.load(fp=json_file)
        self._test_update_object(url, put_body)
        self.intervention.refresh_from_db()

        put_props = put_body["properties"]
        put_geom = geos.fromstr(json.dumps(put_body))
        put_geom.transform(DEFAULT_SRID_RLP)
        self.assertEqual(put_geom, self.intervention.geometry.geom)
        self.assertEqual(put_props["title"], self.intervention.title)
        self.assertNotEqual(modified_on, self.intervention.modified)
        self.assertEqual(put_props["responsible"]["registration_file_number"], self.intervention.responsible.registration_file_number)
        self.assertEqual(put_props["responsible"]["conservation_file_number"], self.intervention.responsible.conservation_file_number)
        self.assertEqual(put_props["legal"]["registration_date"], str(self.intervention.legal.registration_date))
        self.assertEqual(put_props["legal"]["binding_date"], str(self.intervention.legal.binding_date))

    def test_update_compensation(self):
        """ Tests api update

        Returns:

        """
        self.compensation.intervention = self.intervention
        self.compensation.save()
        self.intervention.share_with_user(self.superuser)

        modified_on = self.compensation.modified
        url = reverse("api:v1:compensation", args=(str(self.compensation.id),))
        json_file_path = "api/tests/v1/update/compensation_update_put_body.json"
        with open(json_file_path) as json_file:
            put_body = json.load(fp=json_file)
            put_body["properties"]["intervention"] = str(self.intervention.id)
        self._test_update_object(url, put_body)
        self.compensation.refresh_from_db()

        put_props = put_body["properties"]
        put_geom = geos.fromstr(json.dumps(put_body))
        put_geom.transform(DEFAULT_SRID_RLP)
        self.assertEqual(put_geom, self.compensation.geometry.geom)
        self.assertEqual(put_props["title"], self.compensation.title)
        self.assertNotEqual(modified_on, self.compensation.modified)
        self.assertEqual(put_props["is_cef"], self.compensation.is_cef)
        self.assertEqual(put_props["is_coherence_keeping"], self.compensation.is_coherence_keeping)
        self.assertEqual(put_props["is_pik"], self.compensation.is_pik)
        self.assertEqual(len(put_props["actions"]), self.compensation.actions.count())
        self.assertEqual(len(put_props["before_states"]), self.compensation.before_states.count())
        self.assertEqual(len(put_props["after_states"]), self.compensation.after_states.count())
        self.assertEqual(len(put_props["deadlines"]), self.compensation.deadlines.count())

    def test_update_ecoaccount(self):
        """ Tests api update

        Returns:

        """
        self.eco_account.share_with_user(self.superuser)

        modified_on = self.eco_account.modified
        url = reverse("api:v1:ecoaccount", args=(str(self.eco_account.id),))
        json_file_path = "api/tests/v1/update/ecoaccount_update_put_body.json"
        with open(json_file_path) as json_file:
            put_body = json.load(fp=json_file)
        self._test_update_object(url, put_body)
        self.eco_account.refresh_from_db()

        put_props = put_body["properties"]
        put_geom = geos.fromstr(json.dumps(put_body))
        put_geom.transform(DEFAULT_SRID_RLP)
        self.assertEqual(put_geom, self.eco_account.geometry.geom)
        self.assertEqual(put_props["title"], self.eco_account.title)
        self.assertNotEqual(modified_on, self.eco_account.modified)
        self.assertEqual(put_props["deductable_surface"], str(self.eco_account.deductable_surface))
        self.assertEqual(put_props["responsible"]["conservation_office"], self.eco_account.responsible.conservation_office)
        self.assertEqual(put_props["responsible"]["conservation_file_number"], self.eco_account.responsible.conservation_file_number)
        self.assertEqual(put_props["responsible"]["handler"]["detail"], self.eco_account.responsible.handler.detail)
        self.assertEqual(put_props["legal"]["agreement_date"], str(self.eco_account.legal.registration_date))
        self.assertEqual(len(put_props["actions"]), self.eco_account.actions.count())
        self.assertEqual(len(put_props["before_states"]), self.eco_account.before_states.count())
        self.assertEqual(len(put_props["after_states"]), self.eco_account.after_states.count())
        self.assertEqual(len(put_props["deadlines"]), self.eco_account.deadlines.count())

    def test_update_ema(self):
        """ Tests api update

        Returns:

        """
        self.ema.share_with_user(self.superuser)

        modified_on = self.ema.modified
        url = reverse("api:v1:ema", args=(str(self.ema.id),))
        json_file_path = "api/tests/v1/update/ema_update_put_body.json"
        with open(json_file_path) as json_file:
            put_body = json.load(fp=json_file)
        self._test_update_object(url, put_body)
        self.ema.refresh_from_db()

        put_props = put_body["properties"]
        put_geom = geos.fromstr(json.dumps(put_body))
        put_geom.transform(DEFAULT_SRID_RLP)
        self.assertEqual(put_geom, self.ema.geometry.geom)
        self.assertEqual(put_props["title"], self.ema.title)
        self.assertNotEqual(modified_on, self.ema.modified)
        self.assertEqual(put_props["responsible"]["conservation_office"], self.ema.responsible.conservation_office)
        self.assertEqual(put_props["responsible"]["conservation_file_number"], self.ema.responsible.conservation_file_number)
        self.assertEqual(put_props["responsible"]["handler"]["detail"], self.ema.responsible.handler.detail)
        self.assertEqual(len(put_props["actions"]), self.ema.actions.count())
        self.assertEqual(len(put_props["before_states"]), self.ema.before_states.count())
        self.assertEqual(len(put_props["after_states"]), self.ema.after_states.count())
        self.assertEqual(len(put_props["deadlines"]), self.ema.deadlines.count())

    def test_update_deduction(self):
        """ Tests api update

        Returns:

        """
        self.deduction.intervention.share_with_user(self.superuser)
        self.deduction.account.share_with_user(self.superuser)

        url = reverse("api:v1:deduction", args=(str(self.deduction.id),))
        json_file_path = "api/tests/v1/update/deduction_update_put_body.json"
        with open(json_file_path) as json_file:
            put_body = json.load(fp=json_file)
            put_body["intervention"] = str(self.deduction.intervention.id)
            put_body["eco_account"] = str(self.deduction.account.id)

        self._test_update_object(url, put_body)
        self.deduction.refresh_from_db()

        self.assertEqual(put_body["intervention"], str(self.deduction.intervention.id))
        self.assertEqual(put_body["eco_account"], str(self.deduction.account.id))
        self.assertEqual(put_body["surface"], self.deduction.surface)

    def test_update_share_intervention(self):
        self.intervention.share_with_user(self.superuser)
        url = reverse("api:v1:intervention-share", args=(str(self.intervention.id),))
        json_file_path = "api/tests/v1/update/intervention_share_update_put_body.json"
        with open(json_file_path) as json_file:
            put_body = json.load(fp=json_file)
            put_body["users"] = [self.user.username]
            put_body["teams"] = [self.team.name]

        self.assertFalse(self.intervention.is_shared_with(self.user))
        self.assertEqual(0, self.intervention.shared_teams.count())

        response = self._run_update_request(url, put_body)
        self.assertEqual(response.status_code, 200, msg=response.content)
        self.intervention.refresh_from_db()

        self.assertEqual(1, self.intervention.shared_teams.count())
        self.assertEqual(2, self.intervention.shared_users.count())
        self.assertEqual(self.team.name, self.intervention.shared_teams.first().name)
        self.assertTrue(self.intervention.is_shared_with(self.user))
