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

from presentation.finance_pptx import finance_pptx
from presentation.mks_pptx import mks_pptx
from presentation.retail_pptx import retail_pptx
from report_maker.calculations.utils import filter_by_date
from report_maker.calculations.grouped_tables import grouped_table
from report_maker.finance_report import finance_report
from report_maker.mks_report import mks_report
from report_maker.retail_report import retail_report
from task_class import CPAReportTask
from utils import (
    get_data_filters,
    proceed_form_value,
    replace_target_metric,
    zip_reports
)

logger = logging.getLogger(__name__)


class RetailTask(CPAReportTask):
    def __init__(self, test_mode=None, type_=None, issue=None):
        super(RetailTask, self).__init__(test_mode, type_, issue)

        self.categories_order = None
        self.report_func = retail_report

        self._run_task_workers()

    def make_presentations(self):
        for region, categories in self.results.iteritems():
            self.results[region].append(retail_pptx(self, categories))

    def zip_results(self):
        zipped_results = []
        for region_name, results in self.results.iteritems():
            f_num = basename(results[0]).replace('.xlsx', '').split('_')[0]
            zipped_results.append(
                zip_reports(results, u'{f_num}_{issue_key}.zip'.format(f_num=f_num, issue_key=self.issue.key)))

        return zipped_results

    def _get_specific_options(self):
        self.ecom = True if self.target in ['CSR', 'ROI'] else False

        self.filter_by = dict()
        self.filter_by['Clicks'] = 'DirectClicks'
        self.filter_by['Conversions'] = 'EcommerceOrderVisits' if self.ecom else self.target

        places = proceed_form_value(self.description['params'].get('places'))
        devices = proceed_form_value(self.description['params'].get('devices'))
        categories = proceed_form_value(self.description['params'].get('campaign_types'))
        if categories:
            self.empty_reports = []

        clients = []
        if self.competitors:
            clients = [self.client] + self.competitors
            clients = [client for client in clients if client]

        self.data_filters = {'Client': clients if clients else None,
                             'Place': get_data_filters(places, 'Place'),
                             'Device': get_data_filters(devices, 'Device'),
                             'Category': get_data_filters(categories, 'Category')}

        self._configurate_report()

    def _configurate_report(self):
        logger.debug('%s: _configurate_report', self.issue.key)
        calculations = self.config['ecom'] if self.ecom else self.config['not_ecom']
        for metrics, options in list(calculations.iteritems()):
            if metrics != self.target and not options.get('default', False):
                del calculations[metrics]

        [replace_target_metric(options, self.target) for metrics, options in calculations.iteritems()]

        self.calculations = calculations

    def get_groupby_order(self, region_id):
        logger.debug('%s: get categories order', self.issue.key)

        tmp_df = self.df.copy()
        tmp_df = filter_by_date(tmp_df, self.periods['period_2'])
        tmp_df = tmp_df[(tmp_df['Regions'].isin([region_id])) & (tmp_df['Client'] != self.client)]

        tmp_df = grouped_table(self, tmp_df, 'Category', 'DirectCost', None)
        tmp_df = tmp_df.sort_values(by='CompDirectCost', ascending=False)

        return list(tmp_df.Category.values)


class MKSTask(CPAReportTask):
    def __init__(self, test_mode=None, type_=None, issue=None):
        super(MKSTask, self).__init__(test_mode, type_, issue)

        self.categories_order = None
        self.report_func = mks_report

        self._run_task_workers()

    def make_presentations(self):
        for region, categories in self.results.iteritems():
            region_ppt = []
            for report_path in categories:
                region_ppt.append(mks_pptx(self, report_path))
            self.results[region] += region_ppt

    def zip_results(self):
        results = []
        for region_results in self.results.values():
            results += region_results

        return [zip_reports(results, u'{}.zip'.format(self.issue.key))]

    def _get_specific_options(self):
        self.filter_by = {
            'Clicks': 'DirectClicks',
            'Conversions': self.target
        }
        self.version = proceed_form_value(self.description['params'].get('version'))

        clients = []
        if self.version == u'клиент':
            clients = [self.client]
        elif self.version == u'категория':
            if self.competitors:
                clients = self.competitors

        elif self.version == u'клиент+конкуренты':
            if self.competitors:
                clients = [self.client] + self.competitors

        self.data_filters = {'Client': clients if clients else None}

        self._configurate_report()

    def _configurate_report(self):
        logger.debug('%s: _configurate_report', self.issue.key)
        calculations = self.config['calculations']
        [replace_target_metric(options, self.target) for metrics, options in calculations.iteritems()]
        calculations[self.target] = {'rng_pref': 'Target', 'sheet_pref': u'Конверсии', 'format': u'{:,.0f}'}

        self.calculations = calculations


class FinanceTask(CPAReportTask):
    def __init__(self, test_mode=None, type_=None, issue=None):
        super(FinanceTask, self).__init__(test_mode, type_, issue)

        self.report_func = finance_report
        self._run_task_workers()

    def make_presentations(self):
        for region, categories in self.results.iteritems():
            self.results[region].append(finance_pptx(self, categories))

    def zip_results(self):
        zipped_results = []
        for region_name, results in self.results.iteritems():
            f_num = basename(results[0]).replace('.xlsx', '').split('_')[0]
            zipped_results.append(
                zip_reports(results, u'{f_num}_{issue_key}.zip'.format(f_num=f_num, issue_key=self.issue.key)))

        return zipped_results

    def _get_specific_options(self):
        self.filter_by = {
            'Clicks': 'DirectClicks',
            'Conversions': self.target
        }
        self.dyn_filter = True if proceed_form_value(
            self.description['params'].get('dyn_filter'), default=u'Нет') in (u'Да', u'Yes') else False

        clients = []
        if self.competitors:
            clients = [self.client] + self.competitors
            clients = [client for client in clients if client]

        self.data_filters = {'Client': clients if clients else None}

        self._configurate_report()

    def _configurate_report(self):
        logger.debug('%s: _configurate_report', self.issue.key)
        calculations = self.config['calculations']
        [replace_target_metric(options, self.target) for metrics, options in calculations.iteritems()]
        calculations[self.target] = {'rng_pref': 'Target', 'sheet_pref': u'Конверсии', 'format': u'{:,.0f}'}

        self.calculations = calculations
