from typing import Optional

from django.http import Http404
from rest_framework.response import Response
from rest_framework.views import APIView

from company.models.company import Company
from company.serializers.company import CompanySerializer, CompanyCreateSerializer
from company.services.company_create_update import CompanyCreateAndUpdateService
from core.mixins import ApiPermissionCheckMixin
from perms.models import Perm


class CompanyApiView(ApiPermissionCheckMixin, APIView):
    action = None
    console_permissions = {'get': [Perm.can_view_company_card], 'post': [Perm.can_edit_company_card]}

    def dispatch(self, request, *args, **kwargs):
        if request.method == 'GET':
            self.action = 'get'
        elif request.method == 'POST':
            self.action = 'post'
        else:
            self.action = None

        return super().dispatch(request, *args, **kwargs)

    def get_company(self) -> Optional[Company]:
        """Return first Compay or None"""
        return Company.objects.first()

    def get(self, request, *args, **kwargs) -> Response:
        """Return date company."""
        company = self.get_company()
        if company is None:
            return Response({"details": "company not initialized"})
        data = CompanySerializer(company).data
        return Response(data)

    def post(self, request, *args, **kwargs) -> Response:
        """Creating or updating company in database."""
        serializer = CompanyCreateSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(serializer.errors, status=400)
        company = self.get_company()
        data = CompanyCreateAndUpdateService(company, serializer.data).save()
        return Response(data, status=200)
