# coding: utf-8
"""xlsx-search_queries"""
from .queries import (
    table_highlight_queries,
    plot_highlight_queries_hist,
    table_top_nonbolded_queries,
    table_top_intersection_by_queries,
    table_dssm_score_queries,
    plot_dssm_score_queries_hist,
    table_top_irrelevant_queries,
    table_top_irrelevant_campaigns,
    table_eshows_share_queries,
    plot_eshows_share_queries_hist,
    table_top_eshows_share_queries,
    table_top_eshows_share_campaigns,
)
from .phrases import (
    table_operators_usage,
    plot_operators_usage,
    plot_operators_usage_p,
    table_top_restricted_phrases,
)
from .overview import table_logins_overview
from .nested_queries import (
    shows_by_words_cnt,
    shows_by_nesting_type,
    new_clicks_by_words_cnt,
    ctr_cpc_from_query_len,
    top_queries_from_nested,
    top_queries_phrases_from_nested,
    total_clicks_from_nested,
    total_cost_from_nested
)
from ..utils import (
    get_report_meta,
    add_sheet_to_xlsx,
    save_report_meta,
    note_maker as note,
    plot_maker as plot
)
from ..configure_reports import CLI_REPORTS_CONFIG, return_show_comments, return_sheet_name, return_sheet_note


def make_builder(fn, sheet_name, sheet_fmt=None, **kw_args):
    """((DataFrame) -> DataFrame, str, [(ExcelWriter, str, DataFrame) -> ExcelWriter], **kw_args) ->
       ((ExcelWriter, DataFrame) -> ExcelWriter)"""
    if sheet_fmt is None:
        sheet_fmt = []
    if not isinstance(sheet_fmt, list):
        raise TypeError("`sheet_fmt` must be iterable or None")

    sheet_note = return_sheet_note("search_queries", sheet_name, **kw_args)
    if sheet_note:
        sheet_fmt += [note(sheet_note)]

    if kw_args.get("sheet_writer"):
        sheet_writer = kw_args["sheet_writer"]
    else:
        sheet_writer = add_sheet_to_xlsx

    def builder(writer, df):
        data_to_save = fn(df)
        if not isinstance(data_to_save, dict) and data_to_save is not None:
            setattr(data_to_save, "show_comments", return_show_comments("search_queries"))

        sheet_writer(writer, data_to_save, sheet_name=return_sheet_name("search_queries", sheet_name),
                     sheet_fmt=sheet_fmt, **kw_args)

    return builder


def return_search_queries_builder(sheet_name):

    if sheet_name == "_Info":
        return [make_builder(get_report_meta,
                             "_Info",
                             sheet_writer=save_report_meta)]

    elif sheet_name == "00_logins_overview":
        return [
            make_builder(lambda df: table_logins_overview(df),
                         "00_logins_overview",
                         index=None,
                         startrow=1
                         ),
            make_builder(lambda df: table_logins_overview(df, show_total=True),
                         "00_logins_overview",
                         index=None,
                         header=False
                         )
        ]

    elif sheet_name == "01_highlight_hist_queries":
        return [
            make_builder(lambda df: table_highlight_queries(df, normalize=False),
                         "01_highlight_hist_queries",
                         startcol=7
                         ),
            make_builder(lambda df: table_highlight_queries(df, normalize=True),
                         "01_highlight_hist_queries",
                         sheet_fmt=[plot_highlight_queries_hist]
                         )
        ]

    elif sheet_name == "01_top_non-bolded_queries":
        return [make_builder(table_top_nonbolded_queries,
                             "01_top_non-bolded_queries",
                             index=None)]

    elif sheet_name == "01_operators_usage":
        return [
            make_builder(
                lambda df: table_operators_usage(df, normalize=False),
                "01_operators_usage",
                sheet_fmt=[
                    lambda w, sh, df: plot_operators_usage(
                        w, sh, cell="A10", df=df)]),
            make_builder(lambda df: table_operators_usage(df, normalize=True),
                         "01_operators_usage",
                         startcol=9,
                         sheet_fmt=[lambda w, sh, df: plot_operators_usage_p(
                             w, sh, cell="P10", df=df)]
                         )
        ]

    elif sheet_name == "01_top_fixed_phrase":
        return [make_builder(lambda df: table_top_restricted_phrases(df, "FixedPhrase"),
                             "01_top_fixed_phrase",
                             index=None)]

    elif sheet_name == "01_top_fixed_form":
        return [make_builder(lambda df: table_top_restricted_phrases(df, "FixedForm"),
                             "01_top_fixed_form",
                             index=None)]

    elif sheet_name == "01_top_fixed_order":
        return [make_builder(lambda df: table_top_restricted_phrases(df, "FixedOrder"),
                             "01_top_fixed_order",
                             index=None)]

    elif sheet_name == "01_top_fixed_stopwords":
        return [make_builder(lambda df: table_top_restricted_phrases(df, "FixedStopwords"),
                             "01_top_fixed_stopwords",
                             index=None)]

    elif sheet_name == "02_nested_queries":
        return [
            make_builder(shows_by_words_cnt,
                         "02_nested_queries",
                         sheet_fmt=[plot(chart_names=['shows_disbalance']),
                                    note(u"Показы по кол-ву слов в ключевой фразе и поисковом запросе")]
                         ),
            make_builder(shows_by_nesting_type,
                         "02_nested_queries",
                         sheet_fmt=[plot(chart_names=['broad_match_share']),
                                    note(u"Показы по кол-ву слов в поисковом запросе в точном "
                                         u"(длина запроса = длине фразы) и широком (длина запроса > длины фразы) "
                                         u"соответствии",
                                         cell="K1")
                                    ],
                         startcol=10
                         ),
            make_builder(new_clicks_by_words_cnt,
                         "02_nested_queries",
                         sheet_fmt=[plot(chart_names=['potential_clicks']),
                                    note(u"Новые клики по кол-ву слов: строки - кол-во слов в ключевой фразе, "
                                         u"столбцы - в поисковом запросе, на пересечении длин фразы и запроса - "
                                         u"новые клики от проработки запросов данной длины, "
                                         u"показы по которым идут по фразам данной длины",
                                         cell="A13")
                                    ],
                         startrow=12
                         ),
            make_builder(total_clicks_from_nested,
                         "02_nested_queries",
                         sheet_fmt=[plot(chart_names=['total_potential']),
                                    note(u"Клики: факт и прогноз на основе текущего CTR и коэфф. улучшения CTR "
                                         u"от проработки вложенных запросов",
                                         cell="K13")
                                    ],
                         startrow=12,
                         startcol=10
                         ),
            make_builder(ctr_cpc_from_query_len,
                         "02_nested_queries",
                         sheet_fmt=[plot(chart_names=['ctr', 'cpc']),
                                    note(u"CTR, CPC по кол-ву слов в поисковом запросе. "
                                         u"Изменение показателей для запросов из 1-го слова всегда = 0 "
                                         u"(проработка невозможна)",
                                         cell="A23")
                                    ],
                         startrow=22
                         ),
            make_builder(total_cost_from_nested,
                         "02_nested_queries",
                         sheet_fmt=[note(u"Затраты: факт и прогноз на основе текущей CPC",
                                         cell="N13")],
                         startrow=12,
                         startcol=13
                         ),
            make_builder(top_queries_phrases_from_nested,
                         "02_nested_queries",
                         sheet_fmt=[note(u"Топ-20 пар (поисковый запрос и ключевая фраза) по кол-ву новых кликов",
                                         cell="K23")],
                         index=None,
                         startcol=10,
                         startrow=22)
        ]

    elif sheet_name == "02_top_nested_queries":
        return [make_builder(top_queries_from_nested,
                             "02_top_nested_queries",
                             index=None)]

    elif sheet_name == "03_top_intersection_by_queries":
        return [make_builder(
            lambda df: table_top_intersection_by_queries(df, match_type="fuzzy"),
            "03_top_intersection_by_queries",
            index=None)
        ]

    elif sheet_name == "03_top_doubles_by_queries":
        return [make_builder(
            lambda df: table_top_intersection_by_queries(df, match_type="exact"),
            "03_top_doubles_by_queries",
            index=None)
        ]

    elif sheet_name == "04_dssm_score_hist_queries":
        return [
            make_builder(lambda df: table_dssm_score_queries(df, normalize=True),
                         "04_dssm_score_hist_queries"
                         ),
            make_builder(lambda df: table_dssm_score_queries(df, normalize=False),
                         "04_dssm_score_hist_queries",
                         startcol=9,
                         sheet_fmt=[plot_dssm_score_queries_hist,
                                    plot(chart_names=['dssm_score_ctr_cpc'])]
                         )
        ]

    elif sheet_name == "04_top_irrel_queries_0_25":
        return [make_builder(
            lambda df: table_top_irrelevant_queries(df, score_from=.0, score_to=.25),
            "04_top_irrel_queries_0_25",
            index=None)
        ]

    elif sheet_name == "04_top_irrel_queries_25_50":
        return [make_builder(
            lambda df: table_top_irrelevant_queries(df, score_from=.25, score_to=.5),
            "04_top_irrel_queries_25_50",
            index=None)
        ]

    elif sheet_name == "04_top_irrel_campaigns":
        return [make_builder(table_top_irrelevant_campaigns,
                             "04_top_irrel_campaigns",
                             index=None)]

    elif sheet_name == "04_eshows_share_queries":
        return [
            make_builder(lambda df: table_eshows_share_queries(df, normalize=True),
                         "04_eshows_share_queries"
                         ),
            make_builder(lambda df: table_eshows_share_queries(df, normalize=False),
                         "04_eshows_share_queries",
                         startcol=9,
                         sheet_fmt=[plot_eshows_share_queries_hist,
                                    plot(chart_names=['eshows_share_ctr_cpc'])]
                         )
        ]

    elif sheet_name == "04_top_eshows_share_queries":
        return [make_builder(
            lambda df: table_top_eshows_share_queries(df, score_from=.0, score_to=1.0),
            "04_top_eshows_share_queries",
            index=None)
        ]

    elif sheet_name == "04_top_eshows_share_campaigns":
        return [make_builder(table_top_eshows_share_campaigns,
                             "04_top_eshows_share_campaigns",
                             index=None)]
    else:
        return []


def make_xlsx_search_queries(sheets):
    sheets = [sheet_name for sheet_name in CLI_REPORTS_CONFIG["search_queries"]["meta"]["sheet_names"]
              if sheet_name in sheets]
    xlsx_search_queries = [return_search_queries_builder(sheet_name) for sheet_name in sheets]
    return sum(xlsx_search_queries, [])
