# coding: utf-8

from datetime import timedelta

from django.conf import settings
from django.core.cache import cache
from django.utils.timezone import now
from django.utils.translation import gettext as _
from rest_framework import exceptions
from rest_framework.response import Response

from procu.api import models
from procu.api.utils import WorkdayChecker, get_phone
from procu.rest import generics
from procu.rest.fields import IntegerField
from procu.rest.permissions import StaffOnly
from procu.wf.api import wiki_format
from . import permissions, serializers


class ResetStaticCache(generics.GenericAPIView):
    permission_classes = (permissions.InternalOnly,)
    authentication_classes = ()

    @staticmethod
    def post(request):
        cache.delete('FRONT_RANDOM')
        return Response({})


class FormDataCreateView(generics.CreateAPIView):
    permission_classes = (StaffOnly,)
    queryset = models.FormData.objects.all()
    serializer_class = serializers.FormData

    def create(self, request, *args, **kwargs):
        # ---------------------------------------------------------------
        # Check current limit for upload rate

        recent_uploads = models.FormData.objects.filter(
            author=request.user, created_at__gt=now() - timedelta(days=1)
        ).count()

        if recent_uploads >= settings.FORM_STORAGE_KEYS_PER_DAY:
            raise exceptions.ValidationError(_('FORM_STORAGE::TOO_MANY'))

        # ---------------------------------------------------------------

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

    def perform_create(self, serializer):
        return serializer.save(author=self.request.user)


class FormDataRetrieveView(generics.RetrieveAPIView):
    permission_classes = (StaffOnly,)
    serializer_class = serializers.FormData
    queryset = models.FormData.objects.all()
    lookup_field = 'key'
    lookup_url_kwarg = 'key'


class DeadlineView(generics.GenericAPIView):
    permission_classes = (StaffOnly,)

    def get(self, request, days):

        field = IntegerField(min_value=1, max_value=120)
        days = field.run_validation(days)

        wc = WorkdayChecker()

        target = now()

        while days:
            target += timedelta(hours=24)
            if wc.is_workday(target.date()):
                days -= 1

        return Response(target)


class PhoneView(generics.GenericAPIView):
    permission_classes = (StaffOnly,)

    @staticmethod
    def get(request):
        username = request.GET.get('username', '')

        try:
            phone = get_phone(username)

        except ValueError:
            phone = ''

        return Response({'phone': phone})


class SectionsView(generics.GenericAPIView):
    permission_classes = (StaffOnly,)

    @staticmethod
    def get(request):

        user = request.user

        sections = [
            {'type': 'link', 'title': _('SECTION::ENQUIRIES'), 'url': '/'}
        ]

        if user.has_perm('api.list_log'):
            sections.append(
                {
                    'type': 'link',
                    'title': _('SECTION::TIMELINE'),
                    'url': '/timeline',
                }
            )

        if user.has_perm('api.progress_enquiry') or user.has_perm(
            'api.all_enquiry'
        ):
            sections.append(
                {
                    'type': 'link',
                    'title': _('SECTION::PRODUCTS'),
                    'url': '/products',
                }
            )

        # ----------------------------------------------------------------------
        # Dashboards

        qs = user.dashboards.values('id', 'name')
        dashboards = [
            {
                'type': 'link',
                'title': dashboard['name'],
                'url': f'/dashboard/{dashboard["id"]}',
            }
            for dashboard in qs
        ]

        dashboards.append(
            {
                'type': 'action',
                'title': _('SECTION::DASHBOARDS_CREATE'),
                'url': '#procu-add-open=dashboard',
                'action': 'dashboard',
            }
        )

        sections.append(
            {
                'type': 'menu',
                'title': _('SECTION::DASHBOARDS'),
                'content': dashboards,
            }
        )

        # ----------------------------------------------------------------------
        # Catalogues

        menu = []

        if user.has_perm('api.list_supplier'):
            menu.append(
                {
                    'type': 'link',
                    'title': _('SECTION::SUPPLIERS'),
                    'url': '/directory/suppliers',
                }
            )

        if user.has_perm('api.list_user'):
            menu.append(
                {
                    'type': 'link',
                    'title': _('SECTION::CONTACTS'),
                    'url': '/directory/contacts',
                }
            )

        if user.has_perm('api.list_currency'):
            menu.append(
                {
                    'type': 'link',
                    'title': _('SECTION::CURRENCIES'),
                    'url': '/directory/currencies',
                }
            )

        if user.has_perm('api.list_address'):
            menu.append(
                {
                    'type': 'link',
                    'title': _('SECTION::ADDRESSES'),
                    'url': '/directory/addresses',
                }
            )

        if user.has_perm('api.list_legalentity'):
            menu.append(
                {
                    'type': 'link',
                    'title': _('SECTION::LEGAL_ENTITIES'),
                    'url': '/directory/legal-entities',
                }
            )

        if user.has_perm('api.list_suppliertag'):
            menu.append(
                {
                    'type': 'link',
                    'title': _('SECTION::SUPPLIER_TAGS'),
                    'url': '/directory/supplier-tags',
                }
            )

        if user.has_perm('api.list_enquirycategory'):
            menu.append(
                {
                    'type': 'link',
                    'title': _('SECTION::ENQUIRY_CATEGORIES'),
                    'url': '/directory/categories',
                }
            )

        if user.has_perm('api.list_unit'):
            menu.append(
                {
                    'type': 'link',
                    'title': _('SECTION::UNITS'),
                    'url': '/directory/units',
                }
            )

        if user.has_perm('api.list_discount'):
            menu.append(
                {
                    'type': 'link',
                    'title': _('SECTION::DISCOUNTS'),
                    'url': '/directory/discounts',
                }
            )

        if menu:
            sections.append(
                {
                    'type': 'menu',
                    'title': _('SECTION::MENU_CATALOGUES'),
                    'content': menu,
                }
            )

        # ----------------------------------------------------------------------
        # OEBS

        sections.append(
            {
                'type': 'menu',
                'title': _('SECTION::OEBS'),
                'content': [
                    {
                        'type': 'link',
                        'title': _('SECTION::OEBS_CFOS'),
                        'url': '/oebs/cfos',
                    },
                    {
                        'type': 'link',
                        'title': _('SECTION::OEBS_TASKS'),
                        'url': '/oebs/tasks',
                    },
                    {
                        'type': 'link',
                        'title': _('SECTION::OEBS_SERVICES'),
                        'url': '/oebs/services',
                    },
                    {
                        'type': 'link',
                        'title': _('SECTION::OEBS_PRODUCT_LINES'),
                        'url': '/oebs/product-lines',
                    },
                    {
                        'type': 'link',
                        'title': _('SECTION::OEBS_PURCHASE_GROUPS'),
                        'url': '/oebs/purchase-groups',
                    },
                ],
            }
        )

        return Response(sections)


class CreateFormsView(generics.GenericAPIView):
    permission_classes = (StaffOnly,)

    @staticmethod
    def get(request):
        forms = []

        if request.user.has_perm('api.create_enquiry'):
            forms.extend(
                [
                    {'type': 'goods', 'title': _('ENQUIRY_CREATE_FORM::GOODS')},
                    {
                        'type': 'services',
                        'title': _('ENQUIRY_CREATE_FORM::SERVICES'),
                    },
                ]
            )

        if request.user.has_perm('api.progress_enquiry'):
            forms.append(
                {'type': 'procu', 'title': _('ENQUIRY_CREATE_FORM::FULL')}
            )

        return Response(forms)


class WFPreview(generics.GenericAPIView):
    permission_classes = (StaffOnly,)
    serializer_class = serializers.WFPreview

    def post(self, request, *args, **kwargs):
        serializer = self.get_serializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        text = serializer.validated_data['message']
        return Response({'html': wiki_format(text, config='intranet')})
