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

from exceller import ExcelDocument
from calculations.mks_tables import standard_competitors_sheet, standard_bench_tables, standard_types_sheets
from calculations.utils import get_gain
from cpa_task.utils import convert_name
from xlsx_worker import fill_info_ws, format_charts, rng_formula_to_address, write_df

logger = logging.getLogger(__name__)


def mks_report(task, df, region, category, **kwargs):
    report_name = u'{f_num}_{client}_{region}_{cat}.xlsx'.format(
        f_num=kwargs.get('f_num'), client=task.client, region=region['region_name'][:50], cat=category)
    report_path = join(dirname(dirname(__file__)), report_name)
    logger.info(u'%s: make %s' % (task.issue.key, report_name))

    report = ExcelDocument(join(dirname(dirname(__file__)), 'templates', task.config['xlsx_template']))
    report = mks_template_cleaner(report, task.version)

    for metric, params in task.calculations.iteritems():
        if type(params['sheet_pref']) != unicode:
            params['sheet_pref'] = params['sheet_pref'].decode('utf-8')

        ws = report[params['sheet_pref']]
        for res in standard_bench_tables(task, df, metric, params):
            write_df(ws, res)
        rngs = [u'Periods', u'Client', u'Comp', u'Client_Search', u'Comp_Search', u'Client_Networks', u'Comp_Networks']
        rngs = [u'{}_{}'.format(params.get('rng_pref', metric), x) for x in rngs]
        rng_formula_to_address(ws, rngs, range(2, 9), 4)

        write_mks_gains(ws)
        for addr in ['C3', 'E3', 'G3', 'M3', 'R3', 'W3', 'M8', 'R8', 'W8']:
            ws[addr].text = task.client

        if task.format_charts and ws.name in [u'Конверсии', u'Расходы', u'CR', u'CPA']:
            charts_config = []
            for k, v in task.config['charts'].iteritems():
                tmp_dict = deepcopy(v)
                tmp_dict['ws_name'] = ws.name
                charts_config.append(tmp_dict)

            format_charts(report, charts_config)

        ws = report[u'{} (типы)'.format(params['sheet_pref'])]
        for res in standard_types_sheets(task, df, metric, params):
            write_df(ws, res)
        for addr in ['C2', 'D8', 'O8', 'C18']:
            ws[addr].text = task.client

        if task.format_charts:
            charts_config = []
            for k, v in task.config['type_charts'].iteritems():
                tmp_dict = deepcopy(v)
                tmp_dict['ws_name'] = ws.name
                charts_config.append(tmp_dict)

            format_charts(report, charts_config)

    write_df(report[u'Конкуренты'], standard_competitors_sheet(task, df))
    if task.version != u'клиент':
        rng_formula_to_address(report[u'Конкуренты'],
                               [u'Clients_p2', u'Target_p2', u'Cost_p2', u'CPA_p2'], range(1, 5), 4)

    info = {'B9': convert_name(task.target, task.config['Targets'], to_local=False),
            'B15': task.client,
            'B20': category,
            'M4': region['region_name'],
            'B26': task.time_detail,
            'B31': task.period['first_date'].strftime('%Y-%m-%d'),
            'D31': task.period['last_date'].strftime('%Y-%m-%d'),

            'B36': task.periods['period_1']['first_date'].strftime('%Y-%m-%d'),
            'C36': task.periods['period_1']['last_date'].strftime('%Y-%m-%d'),

            'D36': task.periods['period_2']['first_date'].strftime('%Y-%m-%d'),
            'E36': task.periods['period_2']['last_date'].strftime('%Y-%m-%d'),

            'B42': task.attribution,
            'B47': task.currency,
            'B52': task.vat
            }
    fill_info_ws(report['Info'], task, info, region)

    report.update_charts_cache(named_to_simple_ranges=True)
    report.save(report_path)

    return report_path


def mks_template_cleaner(report, version):
    for ws in report:
        if ws.name == 'Info':
            for row in [9, 15, 20, 26, 31, 36, 42, 47, 52]:
                ws.clear_value('B{0}:E{0}'.format(row))
            ws.clear_value('M4:N5')

        elif ws.name == u'Конкуренты':
            ws.clear_contents('A3:D13')
            if version == u'клиент':
                for rng_name in [u'Clients_p2', u'Target_p2', u'Cost_p2', u'CPA_p2']:
                    ws.doc.set_named_range(rng_name, u'\'{}\'!$B$1'.format(ws.name))

        elif u'типы' in ws.name:

            for rng in ['C2', 'D8', 'O8', 'C18']:
                if ':' not in rng:
                    rng = '{0}:{0}'.format(rng)
                ws.clear_contents(rng)

            for rng in ['C3:G4', 'C9:H13', 'N9:S14', 'B19:G24']:
                if ':' not in rng:
                    rng = '{0}:{0}'.format(rng)
                ws.clear_contents(rng)

            for rng in ['B3:B4', 'B9:B13', 'M9:Q14', 'B19:E24']:
                ws.clear_value(rng)

        else:
            for rng in ['A4:B18', 'L9:L10', 'Q9:Q10', 'V9:V10']:
                ws.clear_value(rng)

            for rng in ['C3', 'E3', 'G3', 'M3', 'R3', 'W3', 'M8', 'R8', 'W8']:
                if ':' not in rng:
                    rng = '{0}:{0}'.format(rng)
                ws.clear_contents(rng)

            for rng in ['C4:H18', 'L4:O6', 'M9:O10', 'Q4:T6', 'R9:T10', 'V4:Y6', 'W9:Y10']:
                if ':' not in rng:
                    rng = '{0}:{0}'.format(rng)
                ws.clear_contents(rng)

    return report


def write_mks_gains(ws):
    for col_num, col_name in [[13, 'M'], [14, 'N'], [18, 'R'], [19, 'S'], [23, 'W'], [24, 'X']]:
        cell1, cell2 = '%s5' % col_name, '%s4' % col_name
        ws.set_cell_value(6, col_num, get_gain(ws[cell1], ws[cell2], format_=u'{:+,.2%}'))

    ws.set_cell_value(5, 15, get_gain(ws['M5'], ws['N5'], format_=u'{:+,.2%}'))
    ws.set_cell_value(5, 20, get_gain(ws['R5'], ws['S5'], format_=u'{:+,.2%}'))
    ws.set_cell_value(5, 25, get_gain(ws['W5'], ws['X5'], format_=u'{:+,.2%}'))

    return ws
