from django.test import TestCase
from django.contrib.auth.models import User
from django.utils import timezone
from rest_framework import status
from rest_framework.test import APITestCase

from webapp.models import Official, Role, Occupation, Committee
from webapp.serializers import OccupationSerializer


URL = "/api/contacts/"
COMMITTEE = Committee.objects.create(
    name_fi="Viestintä",
    name_en="Communications"
)


def createRoleBoard():
    return Role.objects.create(
        name_fi="Metsuri",
        name_en="The lumberjack",
        is_board=True,
        description_fi="Toimikunta PJ",
        description_en="Committee Chair"
    )


def createRoleNoBoard():
    return Role.objects.create(
        name_fi="Toimari",
        name_en="Official",
        is_board=False,
        description_fi="Toimikunta jäbä",
        description_en="Committee dude(tte)",
        committee=COMMITTEE
    )


def createOccupation(year, role=createRoleNoBoard(), dummydata=1):
    occupation = Occupation.objects.create(
        start_date=timezone.datetime(year, 1, 1),
        end_date=timezone.datetime(year, 12, 31),
        role=role
    )

    occupation.officials.add(
        createPerson(dummydata)
    )

    return occupation


def createPerson(name):
    return Official.objects.create(
        user=User.objects.create_user(f"testi{name}", "test@test.tld", "password123"),
        first_name=f"first{name}",
        last_name=f"last{name}",
        email="test@test.tld",
        phone_number="+358501234567",
        image=""
    )


class ContactsTestCase(APITestCase):
    current_year = timezone.now().year
    old_year = 1970

    def setUp(self):
        createOccupation(self.current_year, role=createRoleBoard(), dummydata=1)
        createOccupation(self.current_year, dummydata=2)
        createOccupation(self.old_year, role=createRoleBoard(), dummydata=3)
        createOccupation(self.old_year, dummydata=4)

    def test_get(self):
        response = self.client.get(f"{URL}", format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        serializer = OccupationSerializer(
            Occupation.by_year(self.current_year),
            many=True
        )
        self.assertEqual(response.data["results"], serializer.data)

    def test_get_by_year(self):
        response = self.client.get(f"{URL}?year={self.old_year}", format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)

        serializer = OccupationSerializer(
            Occupation.by_year(self.old_year),
            many=True
        )

        self.assertEqual(response.data["results"], serializer.data)

    def test_by_year_empty(self):
        response = self.client.get(f"{URL}?year=1971")
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data["results"], [])
