# -*- coding: utf-8 -*-
from templates import read_yml_config


def get_pptx_config(task_type=None, key=None):
    config = read_yml_config('%s_slides.yml' % task_type)
    if key:
        return config[key]
    else:
        return config


def get_slide_config(slide_template, keys_to_format, **kwargs):
    for k, v in kwargs.iteritems():
        keys_to_format[k] = u'{}'.format(v)

    return format_config(slide_template, keys_to_format)


def format_config(slide_template, keys_to_format):
    formatted_config = {}

    for k, v in slide_template.iteritems():
        formatted_config[k] = v
        if type(v) == bool or k == 'format':
            continue

        elif type(v) == dict:
            formatted_config[k] = format_config(v, keys_to_format)

        elif type(v) == list:
            new_v = [unicode(x).format(**keys_to_format) for x in v]
            formatted_config[k] = new_v

        else:
            formatted_config[k] = unicode(v).format(**keys_to_format)

    return formatted_config


def split_template_by_titles(slide_template):
    text_holders = slide_template['text_holders']
    if not isinstance(text_holders['title'], list):
        return [slide_template]

    slide_templates = []
    for t_num, title in enumerate(text_holders['title']):
        tmp = dict()
        tmp['text_holders'] = {}

        for ph_name, content in text_holders.iteritems():
            if (isinstance(content, list) and isinstance(content[0], list)) or ph_name == 'title':
                tmp['text_holders'][ph_name] = content[t_num]
                if slide_template.get('charts'):
                    tmp['charts'] = {}
                    for k, v in slide_template['charts'].iteritems():
                        tmp['charts'][k] = v[t_num] if (isinstance(v, list) and isinstance(v[0], list)) else v

            else:
                tmp['text_holders'][ph_name] = content

        for k, v in slide_template.iteritems():
            if k not in ['text_holders', 'charts']:
                tmp[k] = v

        slide_templates.append(tmp)

    return slide_templates
