# -*- coding: utf-8 -*-
from itertools import izip_longest
from os.path import dirname, join
from pptx.util import Cm
from data_maker import (
    calculate_client_vs_comp,
    calculate_clicks_by_queries
)
from charts import bagel_chart, client_vs_comp_chart


def fill_contents_slide(ppt, conf, categories):
    s_cnt = 0
    for cat_slice in izip_longest(fillvalue=None, *[iter(categories)] * 12):
        s_cnt += 1
        slide = add_slide(ppt, conf)

        for cat_num, cat in enumerate(cat_slice, 1):
            num_holder, text_holdes = [
                get_placeholder_by_name(slide, slide.slide_layout, 'text_num_{}'.format(cat_num)),
                get_placeholder_by_name(slide, slide.slide_layout, 'text_{}'.format(cat_num))
            ]

            if cat:
                num_holder.text_frame.text = u'%02d' % (cat_num + (s_cnt - 1) * 12)
                text_holdes.text_frame.text = cat
            else:
                num_holder.element.getparent().remove(num_holder.element)
                text_holdes.element.getparent().remove(text_holdes.element)

    return ppt


def add_slide(ppt, conf):
    layout = get_layout_by_name(ppt, conf['layout'])
    slide = ppt.slides.add_slide(layout)

    slide = fill_text_holders(slide, conf.get('text_holders', {}))
    if conf.get('note'):
        slide.notes_slide.notes_text_frame.text = conf['note']

    if conf.get('images'):
        for img_name, position in conf['images'].iteritems():
            left, top = Cm(float(position['left'])), Cm(float(position['top']))
            height = Cm(float(position['height']))

            img_path = join(dirname(__file__), 'images', img_name)
            slide.shapes.add_picture(img_path, left, top, height=height)

    return slide


def fill_text_holders(slide, conf):
    for ph_name, content in conf.iteritems():
        if type(content) == list:
            for p_num, text in enumerate(content, 1):
                text_holder = get_placeholder_by_name(
                    slide, slide.slide_layout, '{}_{}'.format(ph_name, p_num))
                text_holder.text_frame.text = text

        else:
            text_holder = get_placeholder_by_name(slide, slide.slide_layout, ph_name)
            text_holder.text_frame.text = content

    return slide


def fill_click_share_slide(df, slide, device):
    for ct_num, client_type in enumerate([u'ТОП по суммарным откруткам', u'Клиент'], 1):
        bagel_chart(
            data=calculate_clicks_by_queries(df, device, client_type),
            placeholder=get_placeholder_by_name(slide, slide.slide_layout, 'chart_%i' % ct_num)
        )

    return slide


def fill_client_vs_comp_slide(df, ppt, conf, queries_type, device):
    metrics = [
        'Shows',
        'Clicks',
        'Cost',
        'CPC',
        'CTR'
    ]

    df = df[df.QueryBrandType == queries_type].copy()

    slide = add_slide(ppt, conf)
    for m_num, metric in enumerate(metrics, 1):
        if metric == 'CPC':
            num_format = '#0.0'
        elif metric == 'CTR':
            num_format = '#0.0%'
        else:
            num_format = '### ### ##0'

        client_vs_comp_chart(
            data=calculate_client_vs_comp(df, device, metric),
            num_format=num_format,
            placeholder=get_placeholder_by_name(slide, slide.slide_layout, 'chart_%i' % m_num)
        )

    return slide


def get_layout_by_name(ppt, lo_name):
    for layout in ppt.slide_layouts:
        if layout.name == lo_name:
            return layout
    return None


def get_placeholder_by_name(slide, layout, ph_name):
    for placeholder in layout.placeholders:
        if placeholder.name == ph_name:
            if ph_name == 'slide_number':
                return placeholder
            else:
                ph_idx = placeholder.placeholder_format.idx
                return slide.placeholders[ph_idx]
    return None
