# -*- coding: utf-8 -*-
import logging
import requests
from six.moves.urllib_parse import urljoin
from six.moves.urllib import parse
from datetime import datetime
from saas.library.python.common_functions import get_datetime_timestamp


class LunaparkJob(object):
    """
        Main class for Lunapark API requests.
    """
    base_url = 'https://lunapark.yandex-team.ru/api/job/'
    LOGGER = logging.getLogger(__name__)
    DEFAULT_HEADERS = {'Content-Type': 'application/json'}
    _CONNECTION = requests.session()
    _CONNECTION.headers = DEFAULT_HEADERS

    def __init__(self, job_num):
        """
            Get Lunapark Job for requests
            :param job_num: Num of job to be recieved
        """
        self.job = job_num
        self.base_url = 'https://lunapark.yandex-team.ru/api/job/{}/'.format(self.job)

    def __getattr__(self, info_type):
        return self.JobInfoResult(urljoin(self.base_url, info_type))

    @property
    def time_range_ms(self):
        summary = self.summary('json')
        if not summary.ok:
            return None
        summary = summary.json()[0]
        start = get_datetime_timestamp(datetime.strptime(summary['fd'], '%Y-%m-%d %H:%M:%S'))*1000
        finish = get_datetime_timestamp(datetime.strptime(summary['td'], '%Y-%m-%d %H:%M:%S'))*1000
        return int(start), int(finish)

    @property
    def time_range(self):
        summary = self.summary('json')
        if not summary.ok:
            return None
        summary = summary.json()[0]
        start = datetime.strptime(summary['fd'], '%Y-%m-%d %H:%M:%S')
        finish = datetime.strptime(summary['td'], '%Y-%m-%d %H:%M:%S')
        return start, finish

    def golovan_links_from_shoot(self, service, ctype, geo):
        time_range = self.time_range_ms
        if time_range is None:
            return {}
        start_time, finish_time = time_range

        searchproxy_search_counter = {
            'signals': [el.format(ctype, service) for el in ['hcount(saas_unistat-times-{}-{}_dhhh)']],
            'hosts': 'ASEARCH', 'itype': 'searchproxy', 'geo': geo}

        searchproxy_5xx = {
            'signals': [el.format(ctype, service) for el in ['saas_unistat-search-{}-{}-5xx_dmmm',
                                                             'saas_unistat-search-{}-{}-exceptions_dmmm',
                                                             'saas_unistat-search-{}-{}-unavailable_dmmm',
                                                             'saas_unistat-search-{}-{}-timeouted_dmmm',
                                                             'saas_unistat-search-{}-{}-not-fetched_dmmm',
                                                             'saas_unistat-search-{}-{}-incomplete_dmmm']],
            'hosts': 'ASEARCH', 'itype': 'searchproxy', 'geo': geo}

        searchproxy_size = {
            'signals': [el.format(ctype, service) for el in
                        ['quant(saas_unistat-search-{}-report-kilobyte-size-{}_dhhh, 50)',
                         'quant(saas_unistat-search-{}-report-kilobyte-size-{}_dhhh, 90)',
                         'quant(saas_unistat-search-{}-report-kilobyte-size-{}_dhhh, 95)',
                         'quant(saas_unistat-search-{}-report-kilobyte-size-{}_dhhh, 99)',
                         'quant(saas_unistat-search-{}-report-kilobyte-size-{}_dhhh, 999)']],
                        'hosts': 'ASEARCH', 'itype': 'searchproxy', 'geo': geo}

        service_backends_counter = {
            'signals': [el.format(ctype, service) for el in
                        ['hcount(saas_unistat-search-times-{}-{}-full_dhhh)']],
            'hosts': 'ASEARCH', 'itype': 'rtyserver', 'geo': geo}

        service_backends_errors = {
            'signals': [el.format(ctype, service) for el in
                        ['saas_unistat-backend-source-{}-{}-unanswers_dmmm',
                         'saas_unistat-backend-search-{}-{}-error_dmmm',
                         'saas_unistat-backend-search-{}-{}-unavailable_dmmm',
                         'saas_unistat-backend-search-{}-{}-fail-on-zero_dmmm',
                         'saas_unistat-backend-search-{}-{}-result-fail_dmmm',
                         'crashes_log-saas_{}-{}_exit_signal_mmmm']],
                        'hosts': 'ASEARCH', 'itype': 'rtyserver', 'geo': geo}

        service_backends_doccount = {
            'signals': [el.format(ctype, service) for el in
                        ['quant(saas_unistat-search-total-doc-count-{}-{}_dhhh, 50)',
                         'quant(saas_unistat-search-total-doc-count-{}-{}_dhhh, 80)',
                         'quant(saas_unistat-search-total-doc-count-{}-{}_dhhh, 90)',
                         'quant(saas_unistat-search-total-doc-count-{}-{}_dhhh, 95)',
                         'quant(saas_unistat-search-total-doc-count-{}-{}_dhhh, 99)',
                         'quant(saas_unistat-search-total-doc-count-{}-{}_dhhh, 999)']],
                        'hosts': 'ASEARCH', 'itype': 'rtyserver', 'geo': geo}

        def transform(dict_signal):
            raw_str = ";".join(['{}={}'.format(key, dict_signal[key]) for key in dict_signal])
            final_str = raw_str.replace(' ', "").replace("'", "").replace("[", "{").replace("]", "}")
            parameters = parse.urlencode({'from': start_time, 'to': finish_time})
            yasm_url = 'https://yasm.yandex-team.ru/chart/'
            return parse.urljoin(yasm_url+final_str, '?' + str(parameters))

        final_links = [transform(signal) for signal in (searchproxy_search_counter, searchproxy_5xx, searchproxy_size,
                                                        service_backends_counter, service_backends_errors, service_backends_doccount)]
        names = ['proxy search & bytimes', 'proxy search-5xx', 'proxy report size & empty perc', 'backend search count & bytimes',
                 'backend search-errors', 'backend search total doccount']
        return {name: link for link, name in zip(final_links, names)}

    class JobInfoResult:
        def __init__(self, url):
            self.url = url

        def __call__(self, frmt, **params):
            return LunaparkJob._CONNECTION.get('{}.{}'.format(self.url, frmt), params=params)
