# coding: utf-8
"""review of recommendations"""
from .configure_reports import return_sheet_name, return_report_sheets
from .utils import get_report_meta
import logging


class Recommendation(object):
    TAB_COLORS = {
        0: None,
        1: "8fd541",  # green
        2: "ffcc00",  # yellow
        3: "fa4628"  # red
    }

    def __init__(self, dataframe, internal_sheet_name, title, snippet, importance_lvl=0, cell="A1"):
        "importance_lvl: 0 - None, 1 - green, 2 - yellow, 3 - red"
        self.title = title
        self.snippet = snippet

        meta = get_report_meta(dataframe)
        possible_sheets = return_report_sheets(meta.get('report_local_name'))
        if internal_sheet_name not in possible_sheets:
            raise ValueError("Unknown value for `internal_sheet_name`: %s" % internal_sheet_name)
        self.tabname = return_sheet_name(meta.get('report_local_name'), internal_sheet_name)

        if not self.TAB_COLORS.get(importance_lvl, False):
            raise ValueError("Wrong value fir `importance_lvl`: %s" % importance_lvl)
        self.tabcolor = self.TAB_COLORS[importance_lvl]
        self.sheetcell = cell

    def __str__(self):
        text = u"Recomendation:\n" + \
               u"  tabname: %s\n" % self.tabname + \
               u"  title: %s\n" % self.title + \
               u"  snippet: %s\n" % self.snippet
        return text.encode("utf-8")


def get_recommendations(df):
    return getattr(df, "report_recommendations", [])


def append_recommendation(df, recommendation, uniq=True):
    if not isinstance(recommendation, Recommendation):
        raise ValueError("Unknown type of `recommendation`: %s" % type(recommendation))
    recs = get_recommendations(df)
    # print recommendation
    if not uniq:
        recs.append(recommendation)
    elif recommendation.tabname not in {x.tabname for x in recs}:
        recs.append(recommendation)
    setattr(df, "report_recommendations", recs)


def try_add_review_sheet(writer, dataframe):
    if not hasattr(dataframe, "report_recommendations"):
        return writer
    meta = get_report_meta(dataframe)
    sheet_name = return_sheet_name(meta.get('report_local_name'), "_Review")
    wb = writer.book
    ws = wb.get_worksheet_by_name(sheet_name)
    if ws is None:
        ws = wb.add_worksheet(sheet_name)

    header = [u"Группа рекомендаций", u"Рекомендация", u"Ссылка"]
    ws.set_column(0, 0, 20)
    ws.set_column(1, 1, 60)
    ws.set_column(2, 2, 30)
    ws.write_row("A1", header)

    recs = get_recommendations(dataframe)
    for idx, rec in enumerate(recs):
        # (row, col): zero indexing
        ws.write_string(1 + idx, 0, rec.title)
        ws.write_string(1 + idx, 1, rec.snippet)
        ws.write_url(1 + idx, 2, "internal:'%s'!%s" % (rec.tabname, rec.sheetcell), tip=rec.tabname)
        if rec.tabcolor:
            tmp_ws = wb.get_worksheet_by_name(rec.tabname)
            tmp_ws.set_tab_color(rec.tabcolor)

    ws.activate()
    logging.info(sheet_name)

    return writer
