# -*- coding: utf-8 -*-


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']

    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 get_layout_by_name(ppt, lo_name):
    for layout in ppt.slide_layouts:
        if layout.name == lo_name:

            return layout


def get_placeholder_by_name(slide, layout, ph_name):
    for placeholder in layout.placeholders:
        if placeholder.name == ph_name:

            ph_idx = placeholder.placeholder_format.idx
            return slide.placeholders[ph_idx]
