# -*- coding: utf-8 -*-
import logging
from os.path import basename, dirname, join

from exceller import ExcelDocument
from mks_tables import insert_tables
from pptx import Presentation
from proceed_config import get_pptx_config, split_template_by_titles, get_slide_config
from report_maker.calculations.utils import to_float
from slides import add_general_slides, add_slide, draw_legend, drop_empty_placeholders, insert_charts
from utils import get_pptx_name, get_pretty_period, round_metric

logger = logging.getLogger(__name__)


def finance_pptx(task, categories):
    ppt_path = join(dirname(dirname(__file__)), u'{}.pptx'.format(get_pptx_name(categories[0])))
    logger.info(u'%s: make %s' % (task.issue.key, basename(ppt_path)))

    ppt = Presentation(join(dirname(dirname(__file__)), 'templates', get_pptx_config(task.type_, 'pptx_template')))

    config = get_pptx_config(task.type_, 'slides')
    ppt_params = fin_ppt_params(task, categories)

    ppt = add_general_slides(
        ppt,
        [{slide: config.get(slide)} for slide in get_pptx_config(task.type_, 'presentation')['preface']],
        **ppt_params
    )

    for cat_num, category_fname in enumerate(categories, 1):
        ppt = add_fin_category_slides(ppt, task, category_fname, cat_num, ppt_params,
                                      enumerate_=False if len(categories) > 1 else True)

    ppt = add_general_slides(
        ppt,
        [{slide: config.get(slide)} for slide in get_pptx_config(task.type_, 'presentation')['end']],
        **ppt_params
    )

    ppt.save(ppt_path)
    return ppt_path


def add_fin_category_slides(ppt, task, xlsx_report_path, cat_num, ppt_params, enumerate_):
    report = ExcelDocument(xlsx_report_path)

    ppt_params['chapter_num'] = u'%02d' % cat_num
    ppt_params['category'] = report['Info']['B20'].text

    slides_yml = get_pptx_config(task.type_)
    ppt_structure = slides_yml['presentation']

    slides = []
    if ppt_params['category'] == u'Суммарные данные':
        ppt_params['chapter_title'] = u'Структура категорий рекламодателя\nСуммарно'

        yml_templates = [{slide: slides_yml['slides'][slide]} for slide in ppt_structure['Overview']]
        for slide_template in yml_templates:
            slide_type = slide_template.keys().pop()
            slide_template = slide_template[slide_type]

            for template in split_template_by_titles(slide_template):
                slide_config = get_slide_config(template, ppt_params)
                slides.append(slide_config)

    else:
        for i, place in enumerate(['Total', 'Search', 'Networks'], 1):
            for k, v in slides_yml['places'][place].iteritems():
                ppt_params[k] = v
            for k, v in get_place_key_metrics(report, place).iteritems():
                ppt_params[k] = v

            if enumerate_:
                ppt_params['chapter_num'] = u'%02d' % i
            else:
                ppt_params['chapter_title'] = u'{}\n{}'.format(ppt_params['category'], ppt_params['chapter_title'])

            for slide_name in ppt_structure[place]:
                slide_template = {slide_name: slides_yml['slides'][slide_name]}
                slide_type = slide_template.keys().pop()
                slide_template = slide_template[slide_type]

                for template in split_template_by_titles(slide_template):
                    slide_config = get_slide_config(template, ppt_params)
                    slides.append(slide_config)

    for slide_config in slides:
        slide = add_slide(ppt, slide_config)
        if slide_config.get('legend'):
            draw_legend(slide, slide_config['legend'], task.lang)

        if slide_config.get('charts'):
            insert_charts(report, slide, slide_config)

        if slide_config.get('tables'):
            insert_tables(slide, slide_config['tables'], **{'task': task, 'report': report})

        drop_empty_placeholders(slide)

    return ppt


def get_region_from_report(xlsx_report_path):
    report = ExcelDocument(xlsx_report_path)
    return report['Info']['M4'].text


def fin_ppt_params(task, categories):
    print task.vat
    params = {
        'name': task.created_by['name'],
        'position': task.created_by['position'],
        'lower_position': task.created_by['position'].lower(),
        'client': task.client,

        'analysis_period': get_pretty_period(task.period['first_date'], task.period['last_date'],
                                             task.time_detail).lower(),
        'period_1': get_pretty_period(task.periods['period_1']['first_date'], task.periods['period_1']['last_date'],
                                      task.time_detail),
        'short_period_1': get_pretty_period(task.periods['period_1']['first_date'],
                                            task.periods['period_1']['last_date'], task.time_detail, short=True),
        'period_2': get_pretty_period(task.periods['period_2']['first_date'].strftime('%Y-%m-%d'),
                                      task.periods['period_2']['last_date'].strftime('%Y-%m-%d'), task.time_detail),
        'short_period_2': get_pretty_period(task.periods['period_2']['first_date'],
                                            task.periods['period_2']['last_date'], task.time_detail, short=True),
        'last_month': get_pretty_period(task.period['last_date'], None, u'Месяцы', short=False),
        'region': get_region_from_report(categories[0]),
        'currency': task.currency,
        'method_target': task.config['method_targets'].get(task.target),
        'attribution': task.attribution.lower(),
        'vat': u'с НДС' if task.vat == u'Да' else u'без НДС',
        'categories': categories if len(categories) > 1 else [u'Суммарно', u'Поиск', u'Сети'],
        'category_cell': 'B20'
    }
    params['l_period_1'] = params['period_1'].lower()
    params['l_period_2'] = params['period_2'].lower()

    for k, v in task.get_client_metrica(task.client).iteritems():
        params[k] = v

    return params


def get_place_key_metrics(report, place):
    params = {}

    if place == 'Total':
        row = 5
    elif place == 'Search':
        row = 17
    else:
        row = 29

    for prefix, sheet_name in zip(['Target', 'CPA', 'CR'], [u'Конверсии', u'CPA', u'CR']):
        ws = report[sheet_name]

        if prefix in ['CPA', 'CR']:
            params['Client%s' % prefix] = u'{}\n{}'.format(
                ws['Z%i' % row].text, ws['S%i' % (row + 1)].text
                if ws['S%i' % (row + 1)].text != 'None' and ws['Z%i' % row].text != u'—' else u'—')
            params['Comp%s' % prefix] = u'{}\n{}'.format(
                ws['AA%i' % row].text, ws['T%i' % (row + 1)].text
                if ws['T%i' % (row + 1)].text != 'None' and ws['AA%i' % row].text != u'—' else u'—')
        else:
            params['Client%s' % prefix] = u'{}\n{}'.format(
                round_value(prefix, ws['S%i' % row].text),
                ws['S%i' % (row + 1)].text if ws['S%i' % (row + 1)].text != 'None' else u'—'
            )
            params['Comp%s' % prefix] = u'{}\n{}'.format(
                round_value(prefix, ws['T%i' % row].text),
                ws['T%i' % (row + 1)].text if ws['T%i' % (row + 1)].text != 'None' else u'—'
            )

    return params


def round_value(prefix, value):
    value = to_float(value)

    cap = None
    if prefix == 'Target':
        value, cap = round_metric(value, 'ru')
    format_ = u'{:.1%}' if prefix == 'CR' else u'{:,.0f}'

    value = format_.format(value).replace(',', ' ').replace('.', ',')
    if cap is not None:
        if ',' in value:
            value = value.rstrip('0').rstrip(',')
        value = u'{} {}'.format(value, cap)

    return value
