# -*- coding: utf-8 -*-
import logging
from datetime import datetime, timedelta
from os.path import dirname, join
from itertools import izip_longest
from pptx import Presentation

from slides_config import get_slide_config, slides_config
from slides import add_slide
from table import add_table, get_min_height


logger = logging.getLogger(__name__)


def make_ppt(worker):
    ppt_path = join(dirname(dirname(__file__)), '{}_{}.pptx'.format(worker.issue.key, worker.lang))
    logger.info('{}: make presentation'.format(worker.issue.key))
    logger.info('{}: {} ad options, {} campaign options'.format(worker.issue.key,
                                                                len(worker.ad_opt_table.index),
                                                                len(worker.camp_opt_table.index)))

    ppt = Presentation(join(dirname(__file__), 'template_2.0.pptx'))
    slides_yml = slides_config()
    ppt = add_general_slides(ppt, slides_yml['first_slides'][worker.lang],
                             **{'name': worker.created_by['name'], 'position': worker.created_by['position'].lower()})

    if len(worker.ad_opt_table.columns) <= 4:
        for rows_slice in izip_longest(
                fillvalue=None,
                *[iter(izip_longest(worker.camp_opt_table.index, worker.ad_opt_table.index))] * 10):

            slide_tables = []
            for t_num, df in enumerate([worker.camp_opt_table, worker.ad_opt_table]):
                rows = [slice[t_num] for slice in rows_slice if slice and slice[t_num]]
                slide_tables.append(df.loc[rows, ])

            if not len([df for df in slide_tables if df.empty is False]) == 0:

                config = get_slide_config(
                    slides_config('slides')[worker.lang]['2_tables'],
                    {'date': get_pretty_date(worker.date, worker.time_detail, worker.lang)})
                for i, df in enumerate(slide_tables):
                    if df.empty:
                        config['text_holders']['subtitle'][i] = u''

                slide = add_slide(ppt, config)

                min_height = get_min_height(slide_tables[0], slide_tables[1])
                slide = add_table(slide, slide_tables[0], lang=worker.lang, min_row_height=min_height)
                slide = add_table(slide, slide_tables[1], lang=worker.lang, min_row_height=min_height, left=34.95)

    else:
        if worker.lang == 'ru':
            titles = [u'Настройки объявлений и групп объявлений', u'Настройки рекламных кампаний']
        else:
            titles = [u'Ad and ad group level settings', u'Campaign settings']

        for title, df in zip(titles, [worker.ad_opt_table, worker.camp_opt_table]):
            for idx_slice in izip_longest(
                    fillvalue=None,
                    *[iter(izip_longest(df.index))] * 10):

                rows = [slice[0] for slice in idx_slice if slice and slice[0]]
                table_df = df.loc[rows, ]

                if not table_df.empty:
                    conf = get_slide_config(slides_config('slides')[worker.lang]['1_table'],
                                            {'title': title,
                                             'date': get_pretty_date(worker.date, worker.time_detail, worker.lang)
                                             })
                    slide = add_table(
                        add_slide(ppt, conf),
                        table_df,
                        lang=worker.lang, width=50,
                        min_col_width=4.23
                    )

    ppt = add_general_slides(ppt, slides_yml['last_slides'][worker.lang],
                             **{'name': worker.created_by['name'], 'position': worker.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)
        add_slide(ppt, conf)

    return ppt


def get_pretty_date(date, time_detail, lang):
    date = datetime.strptime(date, '%Y-%m-%d')

    if time_detail == 'daily':
        return pretty_day(date, lang)

    elif time_detail == 'weekly':
        monday = date
        sunday = monday + timedelta(days=6)

        return u'{} – {}'.format(pretty_day(monday, lang), pretty_day(sunday, lang))


def pretty_day(date, lang):
    months = slides_config('months')[lang]
    if lang == 'ru':
        return u'{} {}\'{}'.format(date.day, months[date.month][:3].lower(), str(date.year)[2:])
    else:
        return u'{} {} {}'.format(date.day, months[date.month][:3], date.year)
