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

from presentation import TEMPLATE_PATH
from data_maker import get_pretty_period, get_method, get_slide_config, slides_config
from fill_slide import (
    add_slide,
    fill_click_share_slide,
    fill_client_vs_comp_slide,
    fill_contents_slide
)


logger = logging.getLogger(__name__)


def make_ppt(task):
    if not task.test_mode:
        task.issue.comments.create(text='Сборка презентации.')

    ppt_path = join(dirname(dirname(__file__)), u'БТЗ_{}.pptx'.format(task.query_params['client']))
    logger.info('create %s', basename(ppt_path))

    ppt = Presentation(TEMPLATE_PATH)
    ppt = add_general_slides(
        ppt,
        slides_config('first_slides'),
        ** {'client': task.query_params['client'],
            'categories': [u'{}, {}'.format(cat, get_pretty_region(region)) for cat, region in product(
                task.categories, task.regions)],
            'name': task.created_by['name'],
            'position': task.created_by['position'].lower(),
            'method': get_method(task.query_params['only_search'], task.query_params['vat'])
            }
    )

    for cat_num, (cat, region) in enumerate(product(task.categories, task.regions), 1):
        cat_worker = task.get_worker(cat, region)
        setattr(cat_worker, 'cat_num', u'%02d' % cat_num)
        ppt = add_cat_to_ppt(ppt, cat_worker)

    ppt = add_general_slides(
        ppt,
        slides_config('last_slides'),
        **{'name': task.created_by['name'],
           'position': task.created_by['position']}
    )

    ppt.save(ppt_path)
    return ppt_path


def add_general_slides(ppt, slides_config, **keys_to_format):
    for conf_template in slides_config:
        slide_type = conf_template.keys().pop()
        logger.info('add general %s slide', slide_type)
        conf_template = conf_template[slide_type]

        conf = get_slide_config(conf_template, keys_to_format)
        if slide_type == 'contents':
            fill_contents_slide(ppt, conf, keys_to_format['categories'])
        else:
            add_slide(ppt, conf)

    return ppt


def add_cat_to_ppt(ppt, cat_worker):
    logger.info(u'{}: add slides for {} in {}'
                .format(cat_worker.issue.key, cat_worker.cat, cat_worker.region)
                )

    currency = cat_worker.query_params['currency']
    if currency == u'рубль':
        currency = u'руб'
    elif currency == u'у.е.':
        currency = u'у.е'

    region = get_pretty_region(cat_worker.region)
    period = get_pretty_period(cat_worker.query_params['first_date'], cat_worker.query_params['last_date'])
    keys_to_format = {
        'client': cat_worker.query_params['client'],
        'cat': cat_worker.cat,
        'region': region,

        'period_note': u'Данные Яндекса. Категория «{category}». {period}. {region}'.format(
            category=cat_worker.cat, period=period, region=region),

        'cur_note': u'Данные Яндекса. Категория «{category}». {period}. Валюта: {currency}. {region}'.format(
            category=cat_worker.cat, period=period, currency=currency,
            region=region),

        'cat_num': cat_worker.cat_num,
        'public_url': cat_worker.get_public_url()
    }
    df = cat_worker.res_dfs[-1]

    slides_yml = slides_config()
    queries_types, devices = slides_yml['queries_types'], slides_yml['devices']
    for conf_template in slides_config('slides'):
        slide_type = conf_template.keys().pop()
        logger.info('add %s slides', slide_type)
        conf_template = conf_template[slide_type]

        options = conf_template.get('options', {})
        by_queries, by_devices = options.get('by_queries_type'), options.get('by_devices')

        if by_queries and by_devices:
            for queries_type, device in product(queries_types, devices):
                logger.info(u'add %s slide for %s on %s' % (slide_type, queries_type, device['local_name']))
                conf = get_slide_config(conf_template, keys_to_format,
                                        **{'queries_type': u'{} запросы'.format(queries_type),
                                           'device': device['ppt_name']
                                           }
                                        )

                if slide_type == 'bench':
                    fill_client_vs_comp_slide(df, ppt, conf, queries_type, device['local_name'])

        elif by_devices:
            for device in devices:
                logger.info(u'add %s slide on %s' % (slide_type, device['local_name']))
                conf = get_slide_config(conf_template, keys_to_format, **{'device': device['ppt_name']})

                if slide_type == 'click_share':
                    fill_click_share_slide(df, add_slide(ppt, conf), device['local_name'])

        else:
            conf = get_slide_config(conf_template, keys_to_format)
            add_slide(ppt, conf)

    return ppt


def get_pretty_region(region):
    return region.replace(u'Москва и Московская область', u'Москва и область').replace(
        u'Санкт-Петербург и Ленинградская область', u'Санкт-Петербург и область')
