# coding: utf-8
"""xlsx-mobile:
  - 05_words_cnt
  - 13_top_words_usage
  - 13_top_words_uppercase
"""
from ..const import EXCEL_MAX_ROWS
from ..xlsx_chart.chart import Chart, chart_add_series, FONT_NAME
from ..utils import phrase_process, is_uppercase_word
from .utils import (
    add_cpc_search,
    add_cpc_rsya,
    add_cpc_total,
    add_ctr_search,
    add_ctr_rsya,
    add_ctr_total
)
import pandas as pd


def table_words_cnt(df, normalize):
    """05_words_cnt"""

    words_cnt = sorted(set(df.WordsCnt.unique()) | set(range(1, 8)))

    df_chart = (df[(df.ShowsSearch > 0)]
                .loc[:, ["ShowsSearch", "ClicksSearch", "CostSearch", "BSPhraseID", "WordsCnt"]]
                .groupby("WordsCnt")
                .agg({
                    "ShowsSearch": pd.np.sum,
                    "ClicksSearch": pd.np.sum,
                    "CostSearch": pd.np.sum,
                    "BSPhraseID": lambda x: x.unique().size}))

    if df_chart.shape[0] == 0:
        return None

    add_cpc_search(df_chart)
    add_ctr_search(df_chart)

    df_chart.rename(
        columns={
            "BSPhraseID": u"Кол-во фраз",
            "ShowsSearch": u"Показы (поиск)",
            "ClicksSearch": u"Клики (поиск)",
            "CostSearch": u"Затраты (поиск)",
            "CPCSearch": u"CPC (поиск)",
            "CTRSearch": u"CTR (поиск)"
        },
        inplace=True)
    df_chart.index.name = u"Кол-во слов во фразе"

    df_chart = df_chart.loc[words_cnt].fillna(pd.np.nan)

    if normalize:
        sum_col = [u"Кол-во фраз", u"Показы (поиск)", u"Клики (поиск)", u"Затраты (поиск)"]
        max_col = [u"CPC (поиск)", u"CTR (поиск)"]
        df_chart.loc[:, sum_col] = df_chart.loc[:, sum_col].apply(lambda x: x / x.sum())
        df_chart.loc[:, max_col] = df_chart.loc[:, max_col].apply(lambda x: x / x.max())

    return df_chart.loc[:, [u"Кол-во фраз",
                            u"Показы (поиск)",
                            u"Затраты (поиск)",
                            u"Клики (поиск)",
                            u"CPC (поиск)",
                            u"CTR (поиск)"]]


def plot_words_cnt(writer, sheet_name, df):
    """(ExcelWriter, str, DataFrame) -> ExcelWriter"""

    sheet = writer.book.get_worksheet_by_name(sheet_name)
    chart = Chart(writer.book, "column", None, u'Длина фраз')

    chart.set_y_axis({
        "name": u"Доля от общего",
        'name_font': {
            "size": 16,
            "bold": False,
            "name": FONT_NAME
        },
        'num_font': {
            "size": 14,
            "bold": False,
            "name": FONT_NAME
        },
        'num_format': '#0%',
        'major_tick_mark': 'none',
        'minor_tick_mark': 'none',
        'line': {
            'none': True
        }
    })

    cols = "BCDE"
    last_row = df.index.size + 1
    for n, col in enumerate(cols):
        chart_add_series(chart, n, {
            'values': u"='{0}'!{1}2:{1}{2}".format(sheet_name, col, last_row),
            "categories": u"='{}'!A2:A{}".format(sheet_name, last_row),
            "name": u"='{0}'!{1}1".format(sheet_name, col),
            "data_labels": {
                "num_format": "#0%"
            }
        })

    sheet.insert_chart('A%s' % (last_row + 2), chart)

    return writer


def plot_words_cnt_ctr_cpc(writer, sheet_name, df):
    """(ExcelWriter, str, DataFrame) -> ExcelWriter"""

    sheet = writer.book.get_worksheet_by_name(sheet_name)
    chart = Chart(writer.book, "column", None, u"Показатели работы")

    chart.set_y_axis({
        "visible": True,
        "name": u"",  # CPC
        'name_font': {
            "size": 16,
            "bold": False,
            "name": FONT_NAME
        },
        'num_font': {
            "size": 14,
            "bold": False,
            "name": FONT_NAME
        },
        'num_format': '#0.0',
        'major_tick_mark': 'none',
        'minor_tick_mark': 'none',
        'line': {
            'none': True
        },
        "label_position": "none",
        "min": 0,
    })
    chart.set_y2_axis({
        "visible": True,
        "name": u"",  # CTR
        'name_font': {
            "size": 16,
            "bold": False,
            "name": FONT_NAME
        },
        'num_font': {
            "size": 14,
            "bold": False,
            "name": FONT_NAME
        },
        'num_format': '#0.0%',
        'major_tick_mark': 'none',
        'minor_tick_mark': 'none',
        'line': {
            'none': True
        },
        "label_position": "none",
        "min": 0,
    })

    last_row = df.index.size + 1
    # CPC (поиск)
    chart_add_series(chart, 0, {
        'values': u"='{0}'!{1}2:{1}{2}".format(sheet_name, "O", last_row),
        "categories": u"='{}'!J2:J{}".format(sheet_name, last_row),
        "name": u"='{0}'!{1}1".format(sheet_name, "O"),
        "data_labels": {
            "num_format": "#0.0"
        },
        "overlap": 0,  # The range is +/- 100. The default is 0
        "gap": 340  # The range is 0 to 500. The default is 150
    })
    # fake series for a margin
    chart_add_series(chart, 1, {
        'values': u"='{0}'!{1}2:{1}{2}".format(sheet_name, "Q", last_row),
        "categories": u"='{}'!J2:J{}".format(sheet_name, last_row),
        "name": u"='{0}'!{1}1".format(sheet_name, "Q"),
        "data_labels": {
            "num_format": "#0.0%"
        },
        "y2_axis": 1
    })
    # CTR (поиск)
    chart_add_series(chart, 1, {
        'values': u"='{0}'!{1}2:{1}{2}".format(sheet_name, "P", last_row),
        "categories": u"='{}'!J2:J{}".format(sheet_name, last_row),
        "name": u"='{0}'!{1}1".format(sheet_name, "P"),
        "data_labels": {
            "num_format": "#0.0%"
        },
        "overlap": -100,
        "gap": 150,
        "y2_axis": 1
    })
    chart.set_legend({
        'position': 'bottom',
        "font": {'size': 14,
                 'bold': False,
                 'name': FONT_NAME},
        'delete_series': [1, 1]})
    sheet.insert_chart("P10", chart)

    return writer


def table_top_words_usage(df):
    """13_top_words_usage"""

    col_stat = [
        "Shows", "Clicks", "Cost", "ShowsSearch", "ClicksSearch", "CostSearch",
        "ShowsRSYA", "ClicksRSYA", "CostRSYA"
    ]
    df_chart = df[["PhraseText"] + col_stat].copy()
    df_chart.PhraseText = df_chart.PhraseText.apply(
        lambda x: map(lambda x: x.strip(), phrase_process(x).split(" ")))

    df_chart = pd.np.concatenate(map(lambda (_, row): [row.set_value("PhraseText", w).tolist() for w in row.PhraseText], df_chart.iterrows()))
    df_chart = pd.DataFrame(df_chart, columns=["Word"] + col_stat)
    df_chart[col_stat] = df_chart[col_stat].astype(float)
    df_chart = df_chart.groupby("Word").sum().sort_values(
        "Clicks", ascending=False).head(EXCEL_MAX_ROWS)
    df_chart["OnlyRSYA"] = df_chart["ShowsSearch"] < 1
    df_chart["OnlySearch"] = df_chart["ShowsRSYA"] < 1
    df_chart = df_chart.round(2)

    add_cpc_search(df_chart)
    add_cpc_rsya(df_chart)
    add_cpc_total(df_chart)
    add_ctr_search(df_chart)
    add_ctr_rsya(df_chart)
    add_ctr_total(df_chart)

    df_chart.rename(
        columns={
            "Shows": u"Показы",
            "Clicks": u"Клики",
            "Cost": u"Затраты",
            "CPC": u"CPC",
            "CTR": u"CTR",
            "ShowsSearch": u"Показы (поиск)",
            "ClicksSearch": u"Клики (поиск)",
            "CostSearch": u"Затраты (поиск)",
            "CPCSearch": u"CPC (поиск)",
            "CTRSearch": u"CTR (поиск)",
            "ShowsRSYA": u"Показы (сети)",
            "ClicksRSYA": u"Клики (сети)",
            "CostRSYA": u"Затраты (сети)",
            "CPCRSYA": u"CPC (сети)",
            "CTRRSYA": u"CTR (сети)",
            "OnlySearch": u"Только поиск",
            "OnlyRSYA": u"Только сети"
        },
        inplace=True)
    df_chart.index.names = [u"Слово из фразы"]

    return df_chart.loc[:, [u"Показы",
                            u"Клики",
                            u"Затраты",
                            u"CPC",
                            u"CTR",
                            u"Показы (поиск)",
                            u"Клики (поиск)",
                            u"Затраты (поиск)",
                            u"CPC (поиск)",
                            u"CTR (поиск)",
                            u"Показы (сети)",
                            u"Клики (сети)",
                            u"Затраты (сети)",
                            u"CPC (сети)",
                            u"CTR (сети)",
                            u"Только поиск",
                            u"Только сети"]]


def table_top_words_uppercase(df):
    """13_top_words_uppercase"""

    col_stat = [
        "Shows", "Clicks", "Cost", "ShowsSearch", "ClicksSearch", "CostSearch",
        "ShowsRSYA", "ClicksRSYA", "CostRSYA"
    ]
    df_chart = df[["Title", "Body"] + col_stat].copy()
    df_chart["BannerText"] = df_chart.apply(
        lambda row: u"%s %s" % (row["Title"], row["Body"]), axis=1)
    df_chart.BannerText = df_chart.BannerText.apply(lambda x: map(lambda x: x.strip(), phrase_process(x, to_lower=False).split(" ")))
    df_chart.drop(["Title", "Body"], inplace=True, axis=1)
    df_chart = pd.np.concatenate(map(lambda (_, row): [row.set_value("BannerText", w).tolist() for w in row.BannerText], df_chart.iterrows()))
    df_chart = pd.DataFrame(df_chart, columns=col_stat + ["Word"])
    df_chart = df_chart[df_chart["Word"].apply(is_uppercase_word)]

    if df_chart.shape[0] == 0:
        return None

    df_chart[col_stat] = df_chart[col_stat].astype(float)
    df_chart = df_chart.groupby("Word").sum().sort_values(
        "Clicks", ascending=False).head(EXCEL_MAX_ROWS)
    df_chart["OnlyRSYA"] = df_chart["ShowsSearch"] < 1
    df_chart["OnlySearch"] = df_chart["ShowsRSYA"] < 1
    df_chart = df_chart.round(2)

    add_cpc_search(df_chart)
    add_cpc_rsya(df_chart)
    add_cpc_total(df_chart)
    add_ctr_search(df_chart)
    add_ctr_rsya(df_chart)
    add_ctr_total(df_chart)

    df_chart.rename(
        columns={
            "Shows": u"Показы",
            "Clicks": u"Клики",
            "Cost": u"Затраты",
            "CPC": u"CPC",
            "CTR": u"CTR",
            "ShowsSearch": u"Показы (поиск)",
            "ClicksSearch": u"Клики (поиск)",
            "CostSearch": u"Затраты (поиск)",
            "CPCSearch": u"CPC (поиск)",
            "CTRSearch": u"CTR (поиск)",
            "ShowsRSYA": u"Показы (сети)",
            "ClicksRSYA": u"Клики (сети)",
            "CostRSYA": u"Затраты (сети)",
            "CPCRSYA": u"CPC (сети)",
            "CTRRSYA": u"CTR (сети)",
            "OnlySearch": u"Только поиск",
            "OnlyRSYA": u"Только сети"
        },
        inplace=True)
    df_chart.index.names = [u"Слово из баннера"]

    return df_chart.loc[:, [u"Показы",
                            u"Клики",
                            u"Затраты",
                            u"CPC",
                            u"CTR",
                            u"Показы (поиск)",
                            u"Клики (поиск)",
                            u"Затраты (поиск)",
                            u"CPC (поиск)",
                            u"CTR (поиск)",
                            u"Показы (сети)",
                            u"Клики (сети)",
                            u"Затраты (сети)",
                            u"CPC (сети)",
                            u"CTR (сети)",
                            u"Только поиск",
                            u"Только сети"]]
