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

"""
import json

from django.urls import reverse

from konova.tests.test_views import BaseTestCase
from django.test.client import Client


class AutocompleteTestCase(BaseTestCase):
    @classmethod
    def setUpTestData(cls):
        super().setUpTestData()
        cls.client = Client()

    def test_user_autocomplete(self):
        self.client.login(username=self.superuser.username, password=self.superuser_pw)
        user_autocomplete_url = reverse("user:share-user-autocomplete")
        username = self.user.username

        # Provide the full name --> success
        data = {
            "q": username
        }
        response = self.client.get(
            user_autocomplete_url,
            data,
        )
        content = json.loads(response.content)
        self.assertEqual(username, content["results"][0]["text"])
        self.assertEqual(str(self.user.id), content["results"][0]["id"])

        # Provide only the first letter --> no result
        data = {
            "q": username[0]
        }
        response = self.client.get(
            user_autocomplete_url,
            data,
        )
        content = json.loads(response.content)
        self.assertEqual([], content["results"])

        # Provide full name + too much --> no result
        data = {
            "q": username + "t"
        }
        response = self.client.get(
            user_autocomplete_url,
            data,
        )
        content = json.loads(response.content)
        self.assertEqual([], content["results"])

    def test_all_autocompletes(self):
        tests = [
            "compensation:acc:autocomplete",
            "intervention:autocomplete",
            "codelist:compensation-action-autocomplete",
            "codelist:compensation-action-detail-autocomplete",
            "codelist:biotope-autocomplete",
            "codelist:biotope-extra-type-autocomplete",
            "codelist:law-autocomplete",
            "codelist:process-type-autocomplete",
            "codelist:registration-office-autocomplete",
            "codelist:conservation-office-autocomplete",
            "user:share-user-autocomplete",
            "user:share-team-autocomplete",
            "user:team-admin-autocomplete",
        ]
        for test in tests:
            self.client.login(username=self.superuser.username, password=self.superuser_pw)
            user_autocomplete_url = reverse(test)
            data = {
                "q": ""
            }
            response = self.client.get(
                user_autocomplete_url,
                data,
            )
            content = json.loads(response.content)
            try:
                content["results"]
            except KeyError:
                self.fail(f"No results returned for autocomplete {test}")
