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

from cpa_task.utils import convert_name
from exceller import ExcelDocument
from pptx import Presentation
from proceed_config import (
    get_pptx_config,
    get_slide_config,
    split_template_by_titles
)
from report_maker.calculations.utils import to_float
from slides import add_general_slides, add_slide, drop_empty_placeholders, insert_charts
from utils import get_pretty_period, get_pptx_name, round_metric

logger = logging.getLogger(__name__)

FORMATS = {
    'DirectCost': u'{:,.1f}',
    'OrderedRevenue': u'{:,.1f}',
    'EcommerceOrderVisits': u'{:,.0f}',
    'GoalVisits': u'{:,.0f}',
    'GoalReaches': u'{:,.0f}',
    'CSR': u'{:,.1%}',
    'ROI': u'{:,.0%}',
    'DirectClicks': u'{:,.0f}',
    'CPC': u'{:,.1f}',
    'CR': u'{:.1%}',
    'CPA': u'{:,.0f}'
}


def retail_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')))
    ppt = add_general_slides(
        ppt,
        get_pptx_config(task.type_, 'first_slides'),
        ** {'client': task.client,
            'name': task.created_by['name'],
            'position': task.created_by['position'].lower(),
            'method': get_retail_method_params(task),
            'categories': categories,
            'task': task
            }
    )

    for cat_num, category_fname in enumerate(categories, 1):
        ppt = add_category_slides(ppt, task, category_fname, cat_num)

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

    ppt.save(ppt_path)
    logger.info('%s: pptx done', task.issue.key)

    return ppt_path


def add_category_slides(ppt, task, xlsx_report_path, cat_num):
    report = ExcelDocument(xlsx_report_path)
    keys_to_format = get_keys_to_format(task, report)
    keys_to_format['cat_num'] = u'%02d' % cat_num

    yml_templates = get_pptx_config(task.type_, 'ecom') if task.ecom else get_pptx_config(task.type_, 'not_ecom')
    yml_templates = yml_templates['client_bench'] if task.client else yml_templates['category_bench']
    for slide_template in yml_templates:
        slide_type = slide_template.keys().pop()
        slide_template = slide_template[slide_type]

        options = slide_template.get('options', {})
        if not options or \
                (options.get('total') and keys_to_format['category'] == u'Суммарные данные') or \
                (options.get('category') and keys_to_format['category'] != u'Суммарные данные'):

            for template in split_template_by_titles(slide_template):
                slide_config = get_slide_config(template, keys_to_format)

                title = slide_config['text_holders']['title']
                if title == u'Распределение по типам площадок' and \
                        keys_to_format['category'] in [u'Ретаргетинговые', u'Смарт-баннеры', u'Динамические']:
                    pass

                elif (title == u'Распределение по типам площадок' and len(task.data_filters['Place']) == 1) or \
                        (title == u'Распределение по типам устройств' and len(task.data_filters['Device']) == 1):
                    pass

                else:
                    slide = add_slide(ppt, slide_config)
                    if slide_config.get('charts'):
                        slide = insert_charts(report, slide, slide_config)

                    drop_empty_placeholders(slide)

    return ppt


def get_retail_method_params(task):
    pptx_config = get_pptx_config(task.type_)

    text_holders = pptx_config['method']['ecom'] if task.ecom else pptx_config['method']['not_ecom']
    about_report = pptx_config['client_bench']['about_report'] if task.client else \
        pptx_config['category_bench']['about_report']

    version_conf = pptx_config['ecom'] if task.ecom else pptx_config['not_ecom']
    target_defs = version_conf.get('target_defs', {}).get(task.target, {})

    for k, v in text_holders.iteritems():
        text_holders[k] = v.format(**{
            'about_report': about_report,
            'lower_target': task.config['method_targets'].get(task.target),
            'target_definition': target_defs.get('text', ''),
            'vat': u'с учётом НДС' if task.vat == u'Да' else u'без учёта НДС',
            'attribution': task.attribution.lower(),
        })

    return {'text_holders': text_holders, 'images': target_defs.get('images', {})}


def get_keys_to_format(task, report):
    info_ws = report['Info']

    region = info_ws['M4'].text
    currency = info_ws['B47'].text.strip().lower()
    period_2 = get_pretty_period(info_ws['D41'].text, info_ws['E41'].text, info_ws['B31'].text)

    keys_to_format = {
        'client': info_ws['B20'].text,
        'currency': currency,
        'category': info_ws['B25'].text,
        'region': region,
        'target': info_ws['B14'].text,
        'period_1': get_pretty_period(info_ws['B41'].text, info_ws['C41'].text, info_ws['B31'].text),
        'period_2': get_pretty_period(info_ws['D41'].text, info_ws['E41'].text, info_ws['B31'].text),
        'short_period_1': get_pretty_period(info_ws['B41'].text, info_ws['C41'].text, info_ws['B31'].text, short=True),
        'short_period_2': get_pretty_period(info_ws['D41'].text, info_ws['E41'].text, info_ws['B31'].text, short=True),
        'period_note': u'Данные Яндекса. Категория «{category}». {period_2}. Валюта: {currency} {region}'.format(
            category=info_ws['B25'].text, period_2=period_2, currency=currency, region=region),
        'date_note': u'Данные Яндекса. Категория «{category}». {last_month}. Валюта: {currency} {region}'.format(
            category=info_ws['B25'].text, last_month=get_pretty_period(info_ws['D36'].text, None, u'Месяцы'),
            currency=currency,
            region=region)
    }

    for k, v in get_key_metrics(task, report).iteritems():
        try:
            if k == 'target_value':
                keys_to_format[k] = FORMATS[task.target].format(to_float(v)).replace(',', ' ').replace('.', ',')

            elif k in ['DirectCost', 'OrderedRevenue']:
                value, cap = round_metric(to_float(v))

                value = FORMATS[k].format(value).replace(',', ' ').replace('.', ',')
                if ',' in value:
                    value = value.rstrip('0').rstrip(',')
                value = u'{} {}'.format(value, cap)
                keys_to_format[k] = value

            else:
                keys_to_format[k] = FORMATS[k].format(to_float(v)).replace(',', ' ').replace('.', ',')
        except ValueError:
            keys_to_format[k] = v

    return keys_to_format


def get_key_metrics(task, report):
    key_metrics = {
        'DirectCost': report[u'Расходы']['I4'].text,
        'target_value': report[u'Конверсии']['I4'].text,
        'DirectClicks': report[u'Клики']['I4'].text,
        'CPC': report[u'CPC']['I4'].text,
        'CR': report[u'CR']['I4'].text,
        'CPA': report[u'CPA']['I4'].text,
    }

    if task.ecom:
        key_metrics = {
            'DirectCost': report[u'Расходы']['I4'].text,
            'OrderedRevenue': report[u'Доходы']['I4'].text,
            'EcommerceOrderVisits': report[u'Конверсии']['I4'].text,
            'target_value': report[convert_name(task.target, task.config['Targets'], False)]['I4'].text,
            'DirectClicks': report[u'Клики']['I4'].text,
            'CPC': report[u'CPC']['I4'].text,
            'CR': report[u'CR']['I4'].text,
            'CPA': report[u'CPA']['I4'].text,
        }
        clicks, conversions = to_float(key_metrics['DirectClicks']), to_float(key_metrics['EcommerceOrderVisits'])
        if clicks >= 0. and conversions == 0.:
            key_metrics['CPA'] = u'—'
        if clicks == 0. and conversions >= 0.:
            key_metrics['CR'] = u'—'

    else:
        clicks, conversions = to_float(key_metrics['DirectClicks']), to_float(key_metrics['target_value'])
        if clicks >= 0. and conversions == 0.:
            key_metrics['CPA'] = u'—'
        if clicks == 0. and conversions >= 0.:
            key_metrics['CR'] = u'—'

    return key_metrics
