# coding: utf-8
"""xlsx-keywords"""
from .campaign_stat import (
    table_total_campaigns_stat,
    table_campaigns_overview,
    table_used_strategies_report,
    table_campaigns_type,
    table_list_campaigns_type
)
from .highlight import (
    table_highlight_type_phrases,
    plot_highlight_type_phrases,
    table_highlight_hist,
    plot_highlight_hist,
    table_highlight_type_campaign
)
from .words import (
    table_words_cnt
)
from .templates import (
    table_templates_incorrect_usage,
    table_templates_status,
    table_display_url_has_template,
    table_wo_display_url
)
from .img_shapes import (
    table_img_shapes,
    table_img_area,
    plot_img_area,
    table_img_types,
    plot_img_type,
    plot_img_type_p,
    table_img_types_width,
    table_img_types_detailed,
    table_img_proportions,
    table_rsya_banners_wo_img,
    table_rsya_banners_small_img,
    table_group_img_formats,
    table_rsya_groups_by_img_formats
)
from .timetarget import (
    table_avg_time_target,
    use_time_target_campaigns
)
from .phrases import (  # noqa: F401
    table_top_nonbolded_phrases,
    table_operators_usage,
    plot_operators_usage,
    plot_operators_usage_p,
    table_top_restricted_phrases,
    table_top_phrases_lost_clicks,
    table_top_phrases_strange_pos,
    table_top_cpc_phrases
)
from .banners import (
    table_sitelinks_cnt,
    table_bids_sl_count_lt,
    table_description_sl_cnt,
    table_top_banners_zero_description,
    table_top_banners_navig_incorrect,
    table_callouts_cnt,
    table_callouts_detail,
    table_top_banners_zero_callouts,
    table_top_banners_has_uppercase,
    table_top_banners_desktop_type_incorrect,
    table_top_banners_mobile_type_incorrect
)
from .group_stat import (
    table_group_banners_count,
    table_group_just_one_banner,
    table_group_phrases_count,
    table_group_just_one_phrase,
)
from .vcard import (
    table_vcard_usage,
    table_banners_wo_vcard
)
from ..xlsx_chart.chart import colorize_table_rows
from ..configure_reports import CLI_REPORTS_CONFIG, return_show_comments, return_sheet_name, return_sheet_note
from ..utils import (
    get_report_meta,
    save_report_meta,
    add_sheet_to_xlsx,
    note_maker as note,
    plot_maker as plot
)


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("keywords", 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("keywords"))

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

    return builder


def return_keywords_builder(sheet_name):

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

    elif sheet_name == "00_total_campaigns_stat":
        return [make_builder(table_total_campaigns_stat,
                             "00_total_campaigns_stat",
                             index=None)]

    elif sheet_name == "00_used_strategies":
        return [make_builder(table_used_strategies_report,
                             "00_used_strategies",
                             index=None)]

    elif sheet_name == "00_campaigns_overview":
        return [make_builder(table_campaigns_overview,
                             "00_campaigns_overview",
                             index=None,
                             sheet_fmt=[lambda ws, sh, df:
                                        colorize_table_rows(ws, sh, 1, 6, len(df.index), 11,
                                                            **{'set_cell_size': False,
                                                               'values': [0, 0.5, 1],
                                                               'colors': ['#fa4628', '#ffcc00', '#8fd541'],
                                                               'format': {'num_format': '0.0%'}})]
                             ),
                ]

    elif sheet_name == "00_logins_overview":
        return [
            make_builder(lambda df: table_campaigns_overview(df, groupby="LoginName"),
                         "00_logins_overview",
                         index=None,
                         startrow=1,
                         sheet_fmt=[lambda ws, sh, df:
                                    colorize_table_rows(ws, sh, 2, 5 + 3, len(df.index) + 1, 10 + 3,
                                                        **{'set_cell_size': False,
                                                           'values': [0, 0.5, 1],
                                                           'colors': ['#fa4628', '#ffcc00', '#8fd541'],
                                                           'format': {'num_format': '0.0%'}})]
                         ),
            make_builder(lambda df: table_campaigns_overview(df, groupby="LoginName", show_total=True),
                         "00_logins_overview",
                         index=None,
                         header=False,
                         sheet_fmt=[lambda ws, sh, df:
                                    colorize_table_rows(ws, sh, 0, 5 + 3, 0, 10 + 3,
                                                        **{'set_cell_size': False,
                                                           'values': [0, 0.5, 1],
                                                           'colors': ['#fa4628', '#ffcc00', '#8fd541'],
                                                           'format': {'num_format': '0.0%'}})]
                         )
        ]

    elif sheet_name == "01_highlight_type":
        return [
            make_builder(
                lambda df: table_highlight_type_phrases(df, normalize=False),
                "01_highlight_type",
                sheet_fmt=[
                    lambda w, sh, df: plot_highlight_type_phrases(
                        w, sh, cell="A8", df=df),
                    plot(chart_names=['highlight_type_cpc_and_ctr'])]
            ),
            make_builder(lambda df: table_highlight_type_phrases(df, normalize=True),
                         "01_highlight_type",
                         startcol=9,
                         sheet_fmt=[plot(chart_names=['highlight_type'])]
                         )
        ]

    elif sheet_name == "01_highlight_hist":
        return [
            make_builder(lambda df: table_highlight_hist(df, normalize=False),
                         "01_highlight_hist",
                         startcol=9
                         ),
            make_builder(lambda df: table_highlight_hist(df, normalize=True),
                         "01_highlight_hist",
                         sheet_fmt=[plot_highlight_hist]
                         )
        ]

    elif sheet_name == "01_campaign_highlight_type":
        return [make_builder(table_highlight_type_campaign,
                             "01_campaign_highlight_type")]

    elif sheet_name == "01_top_non-bolded_phrases":
        return [make_builder(table_top_nonbolded_phrases,
                             "01_top_non-bolded_phrases",
                             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_sitelinks_cnt_S":
        return [
            make_builder(lambda df: table_sitelinks_cnt(df, "Search", normalize=True),
                         "02_sitelinks_cnt_S",
                         sheet_fmt=[plot(chart_names=['sl_usage'])]
                         ),
            make_builder(lambda df: table_sitelinks_cnt(df, "Search", normalize=False),
                         "02_sitelinks_cnt_S",
                         startcol=9,
                         sheet_fmt=[plot(chart_names=['sl_cpc_and_ctr'])]
                         )
        ]

    elif sheet_name == "02_sitelinks_cnt_R":
        return [
            make_builder(lambda df: table_sitelinks_cnt(df, "RSYA", normalize=True),
                         "02_sitelinks_cnt_R",
                         sheet_fmt=[plot(chart_names=['sl_usage'])]
                         ),
            make_builder(lambda df: table_sitelinks_cnt(df, "RSYA", normalize=False),
                         "02_sitelinks_cnt_R",
                         startcol=9,
                         sheet_fmt=[plot(chart_names=['sl_cpc_and_ctr'])]
                         )
        ]

    elif sheet_name == "02_bids_sl_count_lt":
        return [
            make_builder(table_bids_sl_count_lt,
                         "02_bids_sl_count_lt",
                         sheet_fmt=[note(u"Топ баннеров без БС, отсортированных по показам на поиске",
                                         cell="A2")],
                         index=None
                         ),
            make_builder(lambda df: table_bids_sl_count_lt(df, sort_criteria="ShowsRSYA"),
                         "02_bids_sl_count_lt",
                         startcol=17,
                         sheet_fmt=[note(u"Топ баннеров без БС, отсортированных по показам в сетях",
                                         cell="R2")],
                         index=None)
        ]

    elif sheet_name == "02_description_sl_cnt":
        return [
            make_builder(lambda df: table_description_sl_cnt(df, normalize=True),
                         "02_description_sl_cnt",
                         sheet_fmt=[plot(chart_names=['sl_description'])]
                         ),
            make_builder(lambda df: table_description_sl_cnt(df, normalize=False),
                         "02_description_sl_cnt",
                         startcol=9,
                         sheet_fmt=[plot(chart_names=['sl_description_cpc_and_ctr'])]
                         )
        ]

    elif sheet_name == "02_description_eq_zero":
        return [make_builder(table_top_banners_zero_description,
                             "02_description_eq_zero",
                             index=None)]

    elif sheet_name == "02_navig_incorrect":
        return [make_builder(table_top_banners_navig_incorrect,
                             "02_navig_incorrect",
                             index=None)]

    elif sheet_name == "03_callouts_cnt_S":
        return [
            make_builder(lambda df: table_callouts_cnt(df, "Search", normalize=True),
                         "03_callouts_cnt_S",
                         sheet_fmt=[plot(chart_names=['callouts', 'callouts_cpc_and_ctr'])]
                         ),
            make_builder(lambda df: table_callouts_cnt(df, "Search", normalize=False),
                         "03_callouts_cnt_S",
                         startcol=9
                         )
        ]

    elif sheet_name == "03_callouts_cnt_R":
        return [
            make_builder(lambda df: table_callouts_cnt(df, "RSYA", normalize=True),
                         "03_callouts_cnt_R",
                         sheet_fmt=[plot(chart_names=['callouts', 'callouts_cpc_and_ctr'])]
                         ),
            make_builder(lambda df: table_callouts_cnt(df, "RSYA", normalize=False),
                         "03_callouts_cnt_R",
                         startcol=9
                         )
        ]

    elif sheet_name == "03_callouts_detail_S":
        return [
            make_builder(lambda df: table_callouts_detail(df, normalize=False, net_type="Search"),
                         "03_callouts_detail_S",
                         startcol=9
                         ),
            make_builder(lambda df: table_callouts_detail(df, normalize=True, net_type="Search"),
                         "03_callouts_detail_S",
                         sheet_fmt=[plot(chart_names=['callouts', 'callouts_cpc_and_ctr'])]
                         )
        ]

    elif sheet_name == "03_callouts_detail_R":
        return [
            make_builder(lambda df: table_callouts_detail(df, normalize=False, net_type="RSYA"),
                         "03_callouts_detail_R",
                         startcol=9
                         ),
            make_builder(lambda df: table_callouts_detail(df, normalize=True, net_type="RSYA"),
                         "03_callouts_detail_R",
                         sheet_fmt=[plot(chart_names=['callouts', 'callouts_cpc_and_ctr'])]
                         )
        ]

    elif sheet_name == "03_top_banners_zero_callouts":
        return [
            make_builder(
                lambda df: table_top_banners_zero_callouts(df, sort_criteria="ShowsSearch"),
                "03_top_banners_zero_callouts",
                sheet_fmt=[note(u"Топ баннеров без уточнений, отсортированных по показам на поиске",
                                cell="A2")],
                index=None),
            make_builder(
                lambda df: table_top_banners_zero_callouts(df, sort_criteria="ShowsRSYA"),
                "03_top_banners_zero_callouts",
                startcol=17,
                sheet_fmt=[note(u"Топ баннеров без уточнений, отсортированных по показам в сетях",
                                cell="R2")],
                index=None)
        ]
    elif sheet_name == "03_top_banners_has_uppercase":
        return [make_builder(table_top_banners_has_uppercase,
                             "03_top_banners_has_uppercase",
                             index=None)]

    elif sheet_name == "04_campaigns_type":
        return [
            make_builder(lambda df: table_campaigns_type(df, normalize=True),
                         "04_campaigns_type"
                         ),
            make_builder(lambda df: table_campaigns_type(df, normalize=False),
                         "04_campaigns_type",
                         startcol=9,
                         sheet_fmt=[plot(chart_names=['campaigns_type', 'campaign_types_cpc_and_ctr'])]
                         )
        ]

    elif sheet_name == "04_list_campaigns_type":
        return [make_builder(table_list_campaigns_type,
                             "04_list_campaigns_type",
                             index=None)]

    elif sheet_name == "05_words_cnt":
        return [
            make_builder(lambda df: table_words_cnt(df, normalize=False),
                         "05_words_cnt",
                         startcol=9
                         ),
            make_builder(lambda df: table_words_cnt(df, normalize=True),
                         "05_words_cnt",
                         sheet_fmt=[plot(chart_names=['words_cnt', 'words_cnt_cpc_and_ctr'])]
                         )
        ]

    elif sheet_name == "06_templates_status":
        return [
            make_builder(lambda df: table_templates_status(df, normalize=True),
                         "06_templates_status"
                         ),
            make_builder(lambda df: table_templates_status(df, normalize=False),
                         "06_templates_status",
                         startcol=10,
                         sheet_fmt=[plot(chart_names=['templates', 'templates_cpc_and_ctr'])]
                         )
        ]

    elif sheet_name == "06_templates_incorrect_usage":
        return [make_builder(table_templates_incorrect_usage,
                             "06_templates_incorrect_usage")]

    elif sheet_name == "06_display_url_S":
        return [
            make_builder(lambda df: table_display_url_has_template(df, net_type="Search", normalize=True),
                         "06_display_url_S",
                         sheet_fmt=[plot(chart_names=['display_url'])]
                         ),
            make_builder(lambda df: table_display_url_has_template(df, net_type="Search", normalize=False),
                         "06_display_url_S",
                         startcol=10,
                         sheet_fmt=[plot(chart_names=['display_url_cpc_and_ctr'])]
                         )
        ]

    elif sheet_name == "06_display_url_R":
        return [
            make_builder(lambda df: table_display_url_has_template(df, net_type="RSYA", normalize=True),
                         "06_display_url_R",
                         sheet_fmt=[plot(chart_names=['display_url'])]
                         ),
            make_builder(lambda df: table_display_url_has_template(df, net_type="RSYA", normalize=False),
                         "06_display_url_R",
                         startcol=10,
                         sheet_fmt=[plot(chart_names=['display_url_cpc_and_ctr'])]
                         )
        ]

    elif sheet_name == "06_wo_display_url":
        return [
            make_builder(lambda df: table_wo_display_url(df, sort_criteria="ShowsSearch"),
                         "06_wo_display_url",
                         sheet_fmt=[note(
                             u"Топ баннеров без отображаемой ссылки, отсортированных по показам на поиске, десктоп",
                             cell="A2"
                         )]),
            make_builder(lambda df: table_wo_display_url(df, sort_criteria="ShowsRSYA"),
                         "06_wo_display_url",
                         sheet_fmt=[note(u"Топ баннеров без отображаемой ссылки, отсортированных по показам в сетях",
                                         cell="R2")],
                         startcol=17
                         )
        ]

    elif sheet_name == "08_img_shapes":
        return [
            make_builder(lambda df: table_img_shapes(df, normalize=False),
                         "08_img_shapes",
                         index=None
                         ),
            make_builder(lambda df: table_img_shapes(df, normalize=True),
                         "08_img_shapes",
                         index=None,
                         startcol=11
                         )
        ]

    elif sheet_name == "08_img_area":
        return [
            make_builder(lambda df: table_img_area(df, normalize=False),
                         "08_img_area",
                         index=None
                         ),
            make_builder(lambda df: table_img_area(df, normalize=True),
                         "08_img_area",
                         index=None,
                         startcol=10,
                         sheet_fmt=[plot_img_area]
                         )
        ]

    elif sheet_name == "08_img_types":
        return [
            make_builder(lambda df: table_img_types(df, normalize=False),
                         "08_img_types",
                         index=True,
                         sheet_fmt=[lambda w, sh, df: plot_img_type(w, sh, cell="A30", df=df)]
                         ),
            make_builder(lambda df: table_img_types(df, normalize=True),
                         "08_img_types",
                         index=True,
                         startcol=11,
                         sheet_fmt=[lambda w, sh, df: plot_img_type_p(w, sh, cell="P30", df=df),
                                    plot(chart_names=['image_types_cpc_and_ctr'])]
                         ),
            make_builder(lambda df: table_img_types_width(df, normalize=False),
                         "08_img_types",
                         index=True,
                         startrow=6
                         ),
            make_builder(lambda df: table_img_types_width(df, normalize=True),
                         "08_img_types",
                         index=True,
                         startrow=6,
                         startcol=11
                         ),
            make_builder(lambda df: table_img_types_detailed(df, normalize=False),
                         "08_img_types",
                         index=True,
                         startrow=11
                         ),
            make_builder(lambda df: table_img_types_detailed(df, normalize=True),
                         "08_img_types",
                         index=True,
                         startrow=11,
                         startcol=11
                         ),
            make_builder(lambda df: table_group_img_formats(df, normalize=False),
                         "08_img_types",
                         index=True,
                         startrow=20,
                         sheet_fmt=[plot(chart_names=['groups_by_formats'])]
                         ),
            make_builder(lambda df: table_group_img_formats(df, normalize=True),
                         "08_img_types",
                         index=True,
                         startrow=20,
                         startcol=11
                         )
        ]
    elif sheet_name == "08_rsya_groups_by_formats":
        return [
            make_builder(table_rsya_groups_by_img_formats,
                         "08_rsya_groups_by_formats",
                         index=False
                         ),
            make_builder(lambda df: table_rsya_groups_by_img_formats(df, table_type='without_images'),
                         "08_rsya_groups_by_formats",
                         index=False,
                         startcol=11,
                         sheet_fmt=[note(u"Только группы, в которых есть объявления с изображениями", cell="L1")]
                         ),
        ]

    elif sheet_name == "08_img_proportions":
        return [
            make_builder(lambda df: table_img_proportions(df, normalize=False),
                         "08_img_proportions",
                         index=True
                         ),
            make_builder(lambda df: table_img_proportions(df, normalize=True),
                         "08_img_proportions",
                         index=True,
                         startcol=10
                         )
        ]

    elif sheet_name == "09_rsya_banners_wo_img":
        return [make_builder(table_rsya_banners_wo_img,
                             "09_rsya_banners_wo_img")]

    elif sheet_name == "09_rsya_banners_small_img":
        return [make_builder(table_rsya_banners_small_img,
                             "09_rsya_banners_small_img"
                             )
                ]

    elif sheet_name == "10_avg_time_target":
        return [make_builder(table_avg_time_target,
                             "10_avg_time_target",
                             sheet_fmt=[lambda ws, sh, _: colorize_table_rows(ws, sh, 1, 2, 7, 25)]
                             )
                ]

    elif sheet_name == "10_use_time_target_campaigns":
        return [make_builder(use_time_target_campaigns,
                             "10_use_time_target_campaigns",
                             index=None)]

    elif sheet_name == "11_top_phrases_lost_clicks":
        return [make_builder(table_top_phrases_lost_clicks,
                             "11_top_phrases_lost_clicks",
                             index=None)]

    elif sheet_name == "12_top_phrases_strange_pos":
        return [make_builder(table_top_phrases_strange_pos,
                             "12_top_phrases_strange_pos",
                             index=None)]

    elif sheet_name == "13_top_cpc_phrases":
        return [make_builder(table_top_cpc_phrases,
                             "13_top_cpc_phrases",
                             index=None)]

    elif sheet_name == "12_group_banners_count":
        return [
            make_builder(
                lambda df: table_group_banners_count(df, normalize=False),
                "12_group_banners_count",
                startcol=8, ),
            make_builder(
                lambda df: table_group_banners_count(df, normalize=True),
                "12_group_banners_count",
                sheet_fmt=[plot(chart_names=['group_banners'])]), ]

    elif sheet_name == "12_group_just_one_banner":
        return [
            make_builder(
                table_group_just_one_banner,
                "12_group_just_one_banner",
                index=None)]

    elif sheet_name == "12_group_phrases_count":
        return [
            make_builder(
                lambda df: table_group_phrases_count(df, normalize=False),
                "12_group_phrases_count",
                startcol=8, ),
            make_builder(
                lambda df: table_group_phrases_count(df, normalize=True),
                "12_group_phrases_count",
                sheet_fmt=[plot(chart_names=['group_phrases'])]),
        ]

    elif sheet_name == "12_group_just_one_phrase":
        return [
            make_builder(
                table_group_just_one_phrase,
                "12_group_just_one_phrase",
                index=None)]

    elif sheet_name == "14_vcard_usage":
        return [
            make_builder(lambda df: table_vcard_usage(df, normalize=True),
                         "14_vcard_usage",
                         sheet_fmt=[plot(chart_names=['vcard_usage'])]
                         ),
            make_builder(lambda df: table_vcard_usage(df, normalize=False),
                         "14_vcard_usage",
                         startcol=10,
                         sheet_fmt=[plot(chart_names=['vcard_cpc_and_ctr'])]
                         )
        ]

    elif sheet_name == "14_banners_wo_vcard":
        return [make_builder(table_banners_wo_vcard,
                             "14_banners_wo_vcard")]

    elif sheet_name == "15_banners_desk_w_mob_stat":
        return [make_builder(table_top_banners_desktop_type_incorrect,
                             "15_banners_desk_w_mob_stat",
                             index=None)]

    elif sheet_name == "15_banners_mob_w_desk_stat":
        return [make_builder(table_top_banners_mobile_type_incorrect,
                             "15_banners_mob_w_desk_stat",
                             index=None)]

    return []


def make_xlsx_keywords(sheets):
    sheets = [sheet_name for sheet_name in CLI_REPORTS_CONFIG["keywords"]["meta"]["sheet_names"]
              if sheet_name in sheets]
    xlsx_keywords = [return_keywords_builder(sheet_name) for sheet_name in sheets]
    return sum(xlsx_keywords, [])
