# -*- coding: utf-8 -*-
from os.path import dirname, join
import pandas as pd
import yaml
import numpy as np

from presentation import RGBColors

MONTHS = {
    1: u'Январь',
    2: u'Февраль',
    3: u'Март',
    4: u'Апрель',
    5: u'Май',
    6: u'Июнь',
    7: u'Июль',
    8: u'Август',
    9: u'Сентябрь',
    10: u'Октябрь',
    11: u'Ноябрь',
    12: u'Декабрь',
}


def calculate_clicks_by_queries(df, device, client_type):
    columns = {
        'total': 'SUM_Clicks',
        'desktop': 'PCClicks',
        'mobile': 'MobClicks'
    }
    sum_col = columns[device]
    categories = [u'Общие', u'Брендовые', u'Конкурентные']

    df = df[df.ClientType == client_type].loc[:, ['QueryBrandType', sum_col]]
    if df.empty:
        return None

    df = (df
          .loc[:, ['QueryBrandType', sum_col]]
          .groupby('QueryBrandType', as_index=True)
          .sum()
          .loc[categories, :]
          )
    df['Share'] = df[sum_col] / df[sum_col].sum() * 100.
    df = df.fillna(0)

    data = {
        'categories': categories,
        'series': [
            {'name': '', 'values': df[sum_col].values}
        ],
        'colors': [RGBColors['blue'], RGBColors['red'], RGBColors['yellow']],
        'data_labels': [u'%.0f%%' % share for share in df['Share'].values]
    }

    return data


def calculate_client_vs_comp(df, device, metric):
    # В df уже отфильтрована нужная категория запросов

    metrics = {
        'Shows': u'Показы',
        'Clicks': u'Клики',
        'Cost': u'Расходы',
        'CPC': u'Цена клика',
        'CTR': u'CTR'
    }

    if metric == 'CPC':
        columns = {
            'total': ['SUM_Cost', 'SUM_Clicks'],
            'desktop': ['PCCost', 'PCClicks'],
            'mobile': ['MobCost', 'MobClicks']
        }
        new_cols = ['Cost', 'Clicks']

    elif metric == 'CTR':
            columns = {
                'total': ['SUM_Clicks', 'SUM_Shows'],
                'desktop': ['PCClicks', 'PCShows'],
                'mobile': ['MobClicks', 'MobShows']
            }
            new_cols = ['Clicks', 'Shows']

    else:
        columns = {
            'total': ['SUM_%s' % metric],
            'desktop': ['PC%s' % metric],
            'mobile': ['Mob%s' % metric]
        }
        new_cols = [metric]

    cols = columns[device]

    try:
        df = (df
              .groupby('ClientType', as_index=True)
              .sum()
              .loc[[u'Конкурент', u'Клиент'], cols]
              .fillna(0)
              )
        df.columns = new_cols

    except KeyError:
        df = pd.DataFrame.from_records([
            [u'Конкурент'] + [0.] * len(new_cols),
            [u'Клиент'] + [0.] * len(new_cols)
        ], columns=['ClientType'] + new_cols)
        df = df.set_index('ClientType')

    if metric == 'CPC':
        client_value = sum(df.loc[[u'Клиент'], 'Cost']) / sum(df.loc[[u'Клиент'], 'Clicks'])
        comp_value = sum(df.loc[[u'Конкурент'], 'Cost']) / sum(df.loc[[u'Конкурент'], 'Clicks'])

    elif metric == 'CTR':
        client_value = sum(df.loc[[u'Клиент'], 'Clicks']) / sum(df.loc[[u'Клиент'], 'Shows'])
        comp_value = sum(df.loc[[u'Конкурент'], 'Clicks']) / sum(df.loc[[u'Конкурент'], 'Shows'])

    else:
        client_value, comp_value = sum(df.loc[[u'Клиент'], metric]), sum(df.loc[[u'Конкурент'], metric])

    client_value = 0 if np.isnan(client_value) else client_value
    comp_value = 0 if np.isnan(comp_value) else comp_value

    if comp_value == 0:
        gain = u''
    else:
        gain = (client_value / comp_value - 1) * 100
        gain = '%+.0f%%' % gain if gain > 0 else '%.0f%%' % gain

    data = {
        'categories': [metrics[metric]],
        'series': [
            {'name': u'Среднее по группе конкурентов', 'values': [comp_value, ], 'color': RGBColors['yellow']},
            {'name': u'Клиент', 'values': [client_value, ], 'color': RGBColors['red']}
        ],
        'gain': gain
    }

    return data


def get_pretty_period(first_date, last_date):
    # YYYYMM
    first_date, last_date = unicode(first_date), unicode(last_date)
    first_month, last_month = int(first_date[-2:]), int(last_date[-2:])

    if first_date == last_date:
        return u'{} {}'.format(MONTHS[first_month], first_date[:4])

    if int(last_date) - int(first_date) == 2 and first_month in [1, 4, 7, 10]:
        q = first_month / 3 + 1
        return u'Q{}\'{}'.format(q, last_date[2:4])

    else:
        return u'{} {} – {} {}'.format(
            MONTHS[first_month], first_date[:4],
            MONTHS[last_month].lower(), last_date[:4],
        )


def slides_config(key=None):
    with open(join((dirname(__file__)), 'slides.yml')) as fd:
        if key:
            return yaml.load(fd)[key]
        else:
            return yaml.load(fd)


def get_slide_config(template, keys_to_format, **kwargs):
    for k, v in kwargs.iteritems():
        keys_to_format[k] = u'{}'.format(v)
    return format_conf(template, keys_to_format)


def format_conf(template, keys_to_format):
    conf = {}

    for k, v in template.iteritems():
        conf[k] = v
        if type(v) == bool:
            continue
        elif type(v) == dict:
            conf[k] = format_conf(v, keys_to_format)
        elif type(v) == list:
            new_v = [unicode(x).format(**keys_to_format) for x in v]
            conf[k] = new_v
        else:
            conf[k] = unicode(v).format(**keys_to_format)

    return conf


def get_method(only_search, vat):
    if only_search == u'да':
        partners_txt = u'(без поисковых партнёров)'
    else:
        partners_txt = u'и поисковым партнёрам'

    if vat:
        money_txt = u'с учётом НДС'
    else:
        money_txt = u'буз учёта НДС'

    return slides_config('method').format(partners_txt, money_txt)
