# coding: utf-8

import logging

from django.db.models import F
from django.utils.encoding import force_text
from startrek_client import exceptions as st_exc

from procu.api import models
from procu.api.enums import ES, PRIORITY
from procu.api.push.utils import to_dict
from procu.api.utils import get_tracker_client

logger = logging.getLogger(__name__)


def fetch_enquiries(user, keys):

    enquiries = (
        models.Enquiry.objects.permitted(user)
        .annotate(deadline_at=F('request__deadline_at'))
        .select_related('manager')
        .filter(key__in=keys)
    )
    enquiries = {e.key: e for e in enquiries}

    objs = {}

    for key in keys:
        objs[key] = obj = {'key': key}

        enquiry = enquiries.get(key)

        if enquiry is None:
            continue

        if enquiry.manager:
            assignee = to_dict(
                enquiry.manager,
                ['username', 'full_name', 'is_staff', 'is_deleted'],
            )
        else:
            assignee = None

        if enquiry.deadline_at:
            deadline_at = enquiry.deadline_at.isoformat()
        else:
            deadline_at = None

        obj.update(
            {
                'title': enquiry.subject,
                'assignee': assignee,
                'priority': {
                    'key': PRIORITY.keys[enquiry.priority],
                    'name': PRIORITY.i18n[enquiry.priority],
                },
                'status': force_text(ES.i18n[enquiry.status]),
                'deadline_at': deadline_at,
            }
        )

    return objs


def fetch_tickets(request, keys):

    if not keys:
        return {}

    try:
        client = get_tracker_client(request=request)
        found = client.issues.find(
            query=' OR '.join(f'(Key: {key} OR Aliases: {key})' for key in keys)
        )

    except st_exc.StartrekError:
        found = []

    issues = {}

    for issue in found:
        issues[issue.key] = issue
        issues.update((alias, issue) for alias in issue.aliases)

    objs = {}

    for key in keys:
        objs[key] = obj = {'key': key}

        issue = issues.get(key)

        if issue is None:
            continue

        issue_raw = issue._value
        assignee = None

        if 'assignee' in issue_raw:
            try:
                data = issue_raw['assignee']._value

                assignee = {
                    'full_name': data['display'],
                    'username': data['id'],
                    'is_staff': True,
                    'is_deleted': False,
                }
            except (KeyError, AttributeError):
                pass

        procu_priority = PRIORITY.from_tracker(issue.priority.key)

        obj.update(
            {
                'key': issue.key,  # can differ from the original key
                'title': issue.summary,
                'assignee': assignee,
                'priority': {
                    'key': PRIORITY.keys[procu_priority],
                    'name': issue.priority.name,
                },
                'status': issue.status.name,
                'status_key': issue.status.key,
                'deadline_at': issue.deadline,
            }
        )

    return objs
