# coding: utf-8
from pptx.enum.text import MSO_ANCHOR, PP_ALIGN
from pptx.oxml.xmlchemy import OxmlElement
from pptx.util import Cm, Pt
from . import PPTX_GIDES, RGBColors


def add_table(slide, data):
    rows, cols = 8, 25

    left, top = 4.41, 7.6
    height, width = 14.8, 58.98
    table = slide.shapes.add_table(rows, cols, Cm(left), Cm(top), Cm(width), Cm(height)).table

    table = fill_table_header(table, range(1, 25))

    for r_idx, row in enumerate(data, 1):
        data_name = row[0]
        cell = table.cell(r_idx, 0)
        cell.text = data_name
        format_cell(cell, alignment=PP_ALIGN.CENTER, fill_color=RGBColors['grey'])

        for c_idx, value in enumerate(row[2:], 1):
            cell = table.cell(r_idx, c_idx)

            value = round(value)
            if value >= 100.:
                fill_color = RGBColors['yellow']
            elif 90. <= value <= 99.:
                fill_color = RGBColors['pale_yellow_1']
            elif 60. <= value <= 89.:
                fill_color = RGBColors['pale_yellow_2']
            else:
                fill_color = RGBColors['white']

            cell.text = u'{:,.0f}'.format(value)
            format_cell(cell, alignment=PP_ALIGN.CENTER, fill_color=fill_color)

    return slide


def fill_table_header(table, header):
    for col_num, column in enumerate(table.columns):
        cell = table.cell(0, col_num)
        if col_num == 0:
            column.width = Cm(2.18)
        else:
            cell.text = unicode(header[col_num - 1])
        set_cell_border(cell, 'top', RGBColors['black'], Pt(3))
        format_cell(
            cell,
            border_width=Pt(3),
            fill_color=RGBColors['white'] if col_num != 0 else RGBColors['grey']
        )
    return table


def format_cell(cell, **kwargs):
    remove_borders(cell, ['right'])
    set_cell_border(
        cell,
        'bottom',
        kwargs.get('border_color', RGBColors['black']),
        kwargs.get('border_width', Pt(1))
    )

    cell.margin_top = Cm(0)
    cell.margin_bottom = Cm(0)

    cell.margin_left = Cm(0)
    cell.margin_right = Cm(0)

    cell.vertical_anchor = MSO_ANCHOR.MIDDLE

    cell.fill.solid()
    cell.fill.fore_color.rgb = kwargs.get('fill_color', RGBColors['white'])

    paragraph = cell.text_frame.paragraphs[0]
    paragraph.alignment = kwargs.get('alignment', PP_ALIGN.CENTER)

    paragraph.font.color.rgb = RGBColors['black']
    paragraph.font.size = Pt(PPTX_GIDES['table_font_size'])
    paragraph.font.name = kwargs.get('font_name', PPTX_GIDES['font_name'])
    paragraph.font.bold = False

    return cell


def SubElement(parent, tag_name, **kwargs):
    element = OxmlElement(tag_name)
    element.attrib.update(kwargs)
    parent.append(element)
    return element


def set_cell_border(cell, border_type, border_color=RGBColors['black'], border_width=Pt(1)):
    lines = {
        'top': 'a:lnT',
        'bottom': 'a:lnB',
        'left': 'a:lnL',
        'right': 'a:lnR'
    }

    tc = cell._tc
    tcPr = tc.get_or_add_tcPr()

    border = SubElement(tcPr, lines[border_type], w=str(border_width), cap='flat', cmpd='sng', algn='ctr')
    solidFill = SubElement(border, 'a:solidFill')
    SubElement(solidFill, 'a:srgbClr', val=str(border_color))
    SubElement(border, 'a:prstDash', val='solid')
    SubElement(border, 'a:round')
    SubElement(border, 'a:headEnd', type='none', w='med', len='med')
    SubElement(border, 'a:tailEnd', type='none', w='med', len='med')

    return border


def remove_borders(cell, border_types=('top', 'bottom', 'left', 'right')):
    lines = {
        'top': 'a:lnT',
        'bottom': 'a:lnB',
        'left': 'a:lnL',
        'right': 'a:lnR'
    }

    for line in [lines[border_type] for border_type in border_types]:
        tc = cell._tc
        tcPr = tc.get_or_add_tcPr()

        border = SubElement(tcPr, line, w=str(12700), cap='flat', cmpd='sng', algn='ctr')
        SubElement(border, 'a:noFill')

    return cell
