# coding: utf-8
from __future__ import unicode_literals

from cab.sources.startrek import get_issues_by_query
from cab.utils import dehydration, env, helpers


HOST = env.choose({
    'production': 'st.yandex-team.ru',
    'testing': 'st.test.yandex-team.ru',
})
URL = 'https://' + HOST

GI_PRIVATE = env.choose({
    'production': '1035',
    'testing': '1159',
})
GI_REGULAR = env.choose({
    'production': '1036',
    'testing': '1160',
})
GI_DEPARTMENT = env.choose({
    'production': '1037',
    'testing': '1161',
})
GI_COMPANY = env.choose({
    'production': '1038',
    'testing': '1162',
})
GI_OKR = env.choose({
    'production': '1039',
    'testing': '1163',
})

GI = {
    GI_REGULAR: 'regular',
    GI_DEPARTMENT: 'department',
    GI_COMPANY: 'company',
    GI_PRIVATE: 'private',
    GI_OKR: 'okr',
}

GS_DRAFT = 'draft'
GS_NORMAL = 'asPlanned'
GS_RISK = 'withRisks'
GS_BLOCKED = 'blockedGoal'
GS_CANCELED = 'cancelled'
GS_NOT_DO = 'notDo'
GS_DONE = 'achieved'
GS_NEW = 'newGoal'
GS_VS_APPROVAL = 'approvalFromTheVsHead'

GS = {
    GS_DRAFT: 'draft',
    GS_NORMAL: 'normal',
    GS_RISK: 'risk',
    GS_BLOCKED: 'blocked',
    GS_CANCELED: 'canceled',
    GS_NOT_DO: 'not_do',
    GS_DONE: 'done',
    GS_NEW: 'new',
    GS_VS_APPROVAL: 'vs_approval',
}

GS_INACTIVE = {
    GS_DRAFT,
    GS_NEW,
    GS_DONE,
    GS_CANCELED,
    GS_NOT_DO,
}

GS_ACTIVE = set(GS) - GS_INACTIVE

GOALS_ACTUAL_DAYS = 180


def get_important_goals(auth, login):
    filters = {
        'Goal Importance': ','.join([
            GI_REGULAR,
            GI_DEPARTMENT,
            GI_COMPANY,
            GI_OKR,
        ]),
        'status': ','.join([
            GS_NORMAL,
            GS_RISK,
            GS_BLOCKED,
            GS_NEW,
        ]),
    }
    return get_goals(auth, login, filters)


def get_in_work_goals(auth, login):
    filters = {
        'Goal Importance': ','.join([
            GI_REGULAR,
            GI_DEPARTMENT,
            GI_COMPANY,
            GI_OKR,
        ]),
        'status': ','.join([
            GS_NORMAL,
            GS_RISK,
            GS_BLOCKED,
            GS_DONE,
            GS_CANCELED,
        ]),
    }
    return get_goals(auth, login, filters)


def get_resolved_goals(auth, login):
    filters = {
        'status': ','.join([
            GS_DONE,
        ]),
    }
    return get_goals(auth, login, filters)


@helpers.timeit
def get_goals(auth, login, filters=None):
    fields = (
        'key',
        'assignee',
        'employees',
        'customers',
        'summary',
        'status',
        'deadline',
        'goalImportance',
        'statusStartTime',
    )
    query = _build_filter_query(login, **filters)
    return list(get_issues_by_query(auth, query=query, fields=fields))


def format_goal_for_response(goal):
    responsible = goal['assignee']
    responsible_name = responsible['display']
    goal_id = goal['key']

    return {
        'id': goal_id,
        'title': goal['summary'],
        'url': build_goal_url(key=goal_id),
        'importance': GI[goal['goalImportance']['id']],
        'status': GS[goal['status']['key']],
        'responsible': dehydration.user(
            display_name=responsible_name,
            first_name=responsible_name.split(' ', 1)[0],
            last_name=responsible_name.split(' ', 1)[1],
            login=responsible['id'],
        ),
        'deadline': goal['deadline'],
    }


def build_goal_url(**params):
    return URL + '/%s' % params['key']


def build_filter_url(auth, **params):
    query = _build_filter_query(auth.login, **params)
    issue_keys = set(i['key'] for i in get_issues_by_query(auth, query=query, fields=('key',)))

    url = URL + '/issues/?_q' + '+OR+'.join([
        '"key":"%s"' % key
        for key in issue_keys
    ])
    return url


def _build_filter_query(login, **filters):
    filters = filters or {}
    filters['queue'] = 'GOALZ'

    person_filters = {
        'assignee': login,
        'participants': login,
        'customers': login,
    }
    query = '({})'.format(' OR '.join('"%s": "%s@"' % (key, value) for key, value in person_filters.items()))
    if filters:
        query += ' AND {}'.format(' AND '.join('"%s": %s' % (key, value) for key, value in filters.items()))
    return query
