# coding: utf-8

from django.conf import settings
from django.db.models import F
from django.utils.translation import gettext_lazy as _

from procu.api import models
from procu.api.common.fields import AttachmentField, EmployeeField, TicketsField
from procu.api.enums import LINK
from procu.api.oebs.serializers import (
    CFOBrief,
    ProjectBrief,
    ServiceBrief,
    TaskBrief,
)
from procu.rest import serializers


class Create(serializers.Serializer):
    check_for_nested_writes = False

    queue = serializers.CharField(
        label=_('SCS::QUEUE'), max_length=30, allow_blank=False, required=True
    )

    is_urgent = serializers.BooleanField(label=_('SCS::IS_URGENT'))
    request_np = serializers.BooleanField(label=_('SCS::REQUEST_NP'))
    legal_entity = serializers.PrimaryKeyRelatedField(
        queryset=models.LegalEntity.objects.filter(is_deleted=False),
        label=_('SCS::LEGAL_ENTITY_TO'),
        allow_null=False,
    )
    customer = EmployeeField(label=_('SCS::CUSTOMER'))
    manager = EmployeeField(label=_('SCS::MANAGER'))
    reference = TicketsField(allow_empty=True, label=_('SCS::REFERENCE'))
    terms = serializers.CharField(max_length=255, label=_('SCS::TERMS'))
    subject = serializers.CharField(label=_('SCS::SUBJECT'))
    attachments = AttachmentField(
        many=True, label=_('SCS::ATTACHMENTS'), allow_empty=True, required=False
    )

    cfo = serializers.PKPrettyField(
        allow_null=False,
        serializer=CFOBrief,
        queryset=models.OracleCFO.objects.filter(is_deleted=False),
        label=_('SCS::CFO'),
    )
    project = serializers.PKPrettyField(
        allow_null=True,
        serializer=ProjectBrief,
        queryset=models.OracleProject.objects.filter(is_deleted=False),
        label=_('SCS::PROJECT'),
        required=False,
    )
    task = serializers.PKPrettyField(
        allow_null=True,
        serializer=TaskBrief,
        queryset=models.OracleTask.objects.filter(is_deleted=False),
        label=_('SCS::TASK'),
        required=False,
    )
    service = serializers.PKPrettyField(
        allow_null=True,
        serializer=ServiceBrief,
        queryset=models.OracleService.objects.filter(is_deleted=False),
        label=_('SCS::SERVICE'),
        required=False,
    )
    delivery_at = serializers.CharField(
        label=_('SCS::DELIVERY_AT'),
        max_length=255,
        allow_blank=False,
        required=True,
    )


def get_context(user, enquiry_id, quote_id):

    quote = (
        models.Quote.objects.permitted(user)
        .values(
            'terms',
            legal_entity=F('request__legal_entity'),
            subject=F('request__subject'),
            queue=F('request__legal_entity__tracker_queue'),
        )
        .get(request__enquiry_id=enquiry_id, id=quote_id)
    )

    enquiry = (
        models.Enquiry.objects.values('cfo', 'project', 'task', 'service')
        .annotate(manager=F('manager__username'))
        .get(id=enquiry_id)
    )

    links = list(
        models.Link.objects.filter(
            object__type=LINK.TRACKER, enquiry=enquiry_id
        ).values_list('key', flat=True)
    )

    attachments = list(
        models.Attachment.objects.values('id', 'filename', 'created_at').filter(
            comment__quote_id=quote_id
        )
    )

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

    output = {}

    for f in ('cfo', 'project', 'task', 'service'):
        output[f] = {'id': enquiry[f]} if enquiry[f] else None

    output.update(
        {
            'queue': quote['queue'] or settings.SCS_QUEUE,
            'terms': quote['terms'].get('comment', ''),
            'subject': quote['subject'],
            'manager': enquiry['manager'] or '',
            'reference': links,
            'legal_entity': quote['legal_entity'],
            'attachments': attachments,
        }
    )

    return output
