# -*- coding: utf-8 -*-
import logging

from common.util.decorators import memoized_property
from .plots_base import MobilePlot


class MobileTimelineQuantilesPlot(MobilePlot):
    quantiles = 50, 75, 80, 85, 90, 95, 98, 99, 100
    graphs = quantiles
    xaxis_type = 'datetime'
    title = 'Энергопотребление'

    @memoized_property
    def data(self):
        data = {}
        try:
            assert self.mobile_job_obj
            if self.mobile_job_obj.version == '2':
                sql = '''
                    select
                    intDiv(uts+{test_start}, 1000000)*10000 as t,
                '''
            else:
                sql = '''
                    select
                    intDiv(time, 10000)*10 as t,
                '''
            sql += '''
                round(avg(value), 3),
                round(quantile(0.50)(value), 3),
                round(quantile(0.75)(value), 3),
                round(quantile(0.80)(value), 3),
                round(quantile(0.85)(value), 3),
                round(quantile(0.90)(value), 3),
                round(quantile(0.95)(value), 3),
                round(quantile(0.98)(value), 3),
                round(quantile(0.99)(value), 3),
                round(max(value), 3)
                from volta.{current_table}
                where test_id='{test_id}'
                and key_date='{key_date}'
                group by t
                order by t
            '''
            fetched_data = self.ch_client.select(sql, query_params=self.query_params)

            self.times = [float(v[0]) / 10 for v in fetched_data]

            quantiles = [[v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10]]
                         for v in fetched_data]
            transponed_quantiles = list(zip(*quantiles))

            for q in reversed(self.quantiles):
                i = self.quantiles.index(q)
                data[q] = list(zip(self.times, transponed_quantiles[i]))
            avg = [float(v[1]) for v in fetched_data]
            data['avg'] = list(zip(self.times, avg))
        except:
            logging.exception('')
        return data

    @staticmethod
    def color_mapping(quantile):
        color_map = {
            50: '#f85750',
            75: 'Coral',
            80: 'DarkOrange',
            85: 'Orange',
            90: 'gold',
            95: '#b8e13d',
            98: '#66af5f',
            99: '#7cb3f1',
            100: '#b2b8c8'
        }
        try:
            color = color_map[quantile]
            return color
        except KeyError:
            logging.warning('Unexpected quantile: {}'.format(quantile))
            return None

    def graphs_settings(self):
        settings = [{
            'values': q,
            'title': '{}%'.format(q),
            'type': 'line' if q in (99, 100) else 'area',
            'disabled': q in (99, 100),
            'color': self.color_mapping(q)} for q in reversed(self.quantiles)]
        settings += [{
            'values': 'avg',
            'title': 'avg',
            'disabled': True,
            'type': 'line',
            'color': '#333',
        }]
        return settings

    @property
    def yaxis(self):
        return [{
                'opposite': False,
                'title': {'text': None},
                'graphs': self.graphs_settings()
                }]
