import os
from itertools import zip_longest

from openpyxl import Workbook
from openpyxl.styles import PatternFill, Border, Side, Alignment, Protection, Font

from .utils import ensure_dir, set_file_perms, WORKDIR


def format_season(s):
    if not s or len(s) < 4:
        return s

    # 'FW20' -> 'F20'
    return s[:1] + s[2:]


def format_name(name, gender):
    return '{}-{}'.format(name, gender[:1])


def write_spreadsheet(matches, workdir, file_base):
    if not matches:
        print('write_spreadsheet: no matches.  skipping.')
        return None

    header_font = Font(name='Calibri', size=12, bold=True)
    body_font = Font(name='Calibri', size=12)
    header_fill = PatternFill(start_color="cccccc", end_color="cccccc", fill_type="solid")
    body_fill = PatternFill(start_color="eeeeee", end_color="eeeeee", fill_type="solid")
    thin_side = Side(border_style='thin', color='000000')
    border = Border(bottom=thin_side)

    wb = Workbook()
    ws = wb.active

    # header row
    ws.append(['style number', 'product name', 'season', 'color', 'category', 'size range'])

    # style the header row
    ws.column_dimensions['A'].width = 15
    ws.column_dimensions['B'].width = 30
    ws.column_dimensions['C'].width = 10
    ws.column_dimensions['D'].width = 30
    ws.column_dimensions['E'].width = 15
    ws.column_dimensions['F'].width = 35

    for f in ('A1', 'B1', 'C1', 'D1', 'E1', 'F1'):
        ws[f].font = header_font
        ws[f].fill = header_fill
        ws[f].border = border

    # TODO: sort matches

    seen = {}

    for m in matches:
        # in the case of kids,
        # we might have multiple products in a match
        seasons    = m['season'].lower().split('\n')
        genders    = m['gender'].lower().split('\n')
        names      = m['name'].lower().split('\n')
        materials  = m['material'].lower().split('\n')
        colors     = m['color'].lower().split('\n')
        sizes      = m['size'].lower().split('\n')
        categories = m['category'].lower().split('\n')

        for s, g, n, m, c, sz, ct in zip_longest(seasons, genders, names, materials, colors, sizes, categories, fillvalue=''):
            if not m in seen:
                ws.append([m, format_name(n, g), format_season(s), c, ct, sz])
                seen[m] = True

    # style body
    for row in ws.iter_rows(min_row=2, max_row=None, max_col=None):
        for cell in row:
            cell.font = body_font
            cell.fill = body_fill
            cell.border = border

    # save
    ensure_dir(workdir)
    path = os.path.join(workdir, f"{file_base}.xlsx")
    wb.save(path)
    set_file_perms(path)

    return path
