# coding: utf-8
"""xlsx-mobile:
  - 01_top_non-bolded_phrases
  - 11_top_phrases_lost_clicks
  - 12_top_phrases_strange_pos
  - 13_top_cpc_phrases
"""
from ..const import EXCEL_MAX_ROWS
from ..utils import get_cid_bid, filter_by_adtype, phrase_process
from .utils import (
    add_ctr_spec,
    add_ctr_other
)
import pandas as pd


def table_top_nonbolded_phrases(df):
    """01_top_non-bolded_phrases"""

    df_chart = filter_by_adtype(df, "MOBILE_APP_AD")
    df_chart = df_chart[[
        "BoldedWordsCnt",
        "WordsCnt",
        "ShowsSearch",
        "ClicksSearch",
        "CostSearch",
        "PhraseText",
        "NonBoldedWords",
        "Title",
        "Body",
        "DirectBannerID",
        "CampaignID",
        "CampaignName"]].copy()

    df_chart = df_chart.loc[
        (df_chart.WordsCnt != 0) &
        (df_chart.ShowsSearch > 0) &
        (df_chart.BoldedWordsCnt < df_chart.WordsCnt) &
        (df_chart.NonBoldedWords != ""), :]

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

    df_chart["PhraseBoldShare"] = df_chart.BoldedWordsCnt / df_chart.WordsCnt
    df_chart.drop(["BoldedWordsCnt", "WordsCnt"], axis=1, inplace=True)
    df_chart['ShowsSearchNonBolded'] = ((1 - df_chart['PhraseBoldShare']) * df_chart['ShowsSearch']).astype(int)
    df_chart.sort_values("ShowsSearchNonBolded", ascending=False, inplace=True)
    df_chart['HelperURL'] = df_chart.apply(
        lambda row: get_cid_bid(row["CampaignID"], row["DirectBannerID"]),
        axis=1)
    df_chart["CPCSearch"] = df_chart["CostSearch"] / df_chart["ClicksSearch"]
    df_chart["CTRSearch"] = df_chart["ClicksSearch"] / df_chart["ShowsSearch"]
    df_chart = df_chart[[
        "CampaignID", "CampaignName", "DirectBannerID", "Title", "Body",
        "PhraseText", "NonBoldedWords", "ShowsSearch",
        "ClicksSearch", "CostSearch", "CPCSearch", "CTRSearch", "HelperURL"]]
    df_chart.rename(columns={
        "CampaignID": u"Кампания №",
        "CampaignName": u"Название кампании",
        "DirectBannerID": u"Баннер №",
        "Title": u"Заголовок",
        "Body": u"Объявление",
        "PhraseText": u"Ключевая фраза",
        "NonBoldedWords": u"Неподсвеченное слово",
        "ShowsSearch": u"Показы (поиск)",
        "ClicksSearch": u"Клики (поиск)",
        "CostSearch": u"Затраты (поиск)",
        "CPCSearch": u"CPC (поиск)",
        "CTRSearch": u"CTR (поиск)",
        "HelperURL": u"Ссылка на баннер"},
        inplace=True)

    return df_chart


def table_top_phrases_lost_clicks(df):
    """11_top_phrases_lost_clicks"""

    df_chart = filter_by_adtype(df, "MOBILE_APP_AD")
    df_chart = df_chart.loc[
        (df_chart.ClicksSpec > 0) &
        (df_chart.ClicksSpec <= df_chart.ShowsSpec)].copy()

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

    df_chart = (df_chart.assign(
        PhraseText=lambda x: x.PhraseText.apply(phrase_process))
        [["CampaignID", "CampaignName", "DirectBannerID", "PhraseText",
          "ShowsSpec", "ClicksSpec", "ShowsOther", "ClicksOther"]]
        .groupby(["CampaignID", "CampaignName", "DirectBannerID", "PhraseText"], as_index=False)
        .agg({"ShowsSpec": pd.np.sum,
              "ClicksSpec": pd.np.sum,
              "ShowsOther": pd.np.sum,
              "ClicksOther": pd.np.sum})
        .assign(MaxClicks=lambda x: x.ClicksSpec / x.ShowsSpec * (x.ShowsOther + x.ShowsSpec))
        .assign(LostClicks=lambda x: x.ClicksSpec / x.ShowsSpec * x.ShowsOther - x.ClicksOther)
        .sort_values("LostClicks", ascending=False)
        .head(EXCEL_MAX_ROWS))

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

    add_ctr_spec(df_chart)
    add_ctr_other(df_chart)

    df_chart['HelperUrlBid'] = df_chart.apply(
        lambda row: get_cid_bid(row["CampaignID"], row["DirectBannerID"]),
        axis=1)

    df_chart.rename(columns={
        "CampaignID": u"Кампания №",
        "CampaignName": u"Название кампании",
        "DirectBannerID": u"Баннер №",
        "PhraseText": u"Ключевая фраза",
        "HelperUrlBid": u"Ссылка на баннер",
        "ShowsSpec": u"Показы (спец.)",
        "ClicksSpec": u"Клики (спец.)",
        "CTRSpec": u"CTR (спец.)",
        "ShowsOther": u"Показы (юж./пр. блок)",
        "ClicksOther": u"Клики (юж./пр. блок)",
        "CTROther": u"CTR (юж./пр. блок)",
        "MaxClicks": u"Максимум кликов",
        "LostClicks": u"Упущенные клики"},
        inplace=True)

    return df_chart.loc[:, [u"Кампания №",
                            u"Название кампании",
                            u"Баннер №",
                            u"Ключевая фраза",
                            u"Ссылка на баннер",
                            u"Показы (спец.)",
                            u"Клики (спец.)",
                            u"CTR (спец.)",
                            u"Показы (юж./пр. блок)",
                            u"Клики (юж./пр. блок)",
                            u"CTR (юж./пр. блок)",
                            u"Максимум кликов",
                            u"Упущенные клики"]]


def table_top_phrases_strange_pos(df):
    """12_top_phrases_strange_pos"""
    df_chart = df.loc[~df.AvgPosShowsOther.isnull(), :].copy()
    try:
        df_chart = df.loc[df.AvgPosShowsOther != "None", :].copy()
    except TypeError:
        pass
    if df_chart.shape[0] == 0:
        return None
    df_chart.AvgPosShowsOther = df_chart.AvgPosShowsOther.astype(float)
    df_chart["ShowsSpecShare"] = df_chart["ShowsSpec"] / df_chart["ShowsSearch"]
    df_chart["CPC_spec"] = df_chart["CostSpec"] / df_chart["ClicksSpec"]
    df_chart["CPC_other"] = df_chart["CostOther"] / df_chart["ClicksOther"]
    df_chart["CPC_ratio"] = df_chart["CPC_spec"] / df_chart["CPC_other"]
    df_chart["CTR_spec"] = df_chart["ClicksSpec"] / df_chart["ShowsSpec"]
    df_chart["CTR_other"] = df_chart["ClicksOther"] / df_chart["ShowsOther"]
    df_chart = (df_chart[(df_chart["ShowsSpecShare"] < .9) &
                         (df_chart["CPC_ratio"] < 2) &
                         (df_chart.AvgPosShowsOther < 4.5) &
                         (df_chart.ShowsOther > 50)]
                [["CampaignID", "CampaignName", "DirectBannerID",
                  "PhraseText", "AvgPosShowsOther", "ShowsOther", "ShowsSpec",
                  "CPC_spec", "CPC_other", "CTR_spec", "CTR_other"]]
                .sort_values("ShowsOther", ascending=False)
                .reset_index(drop=True)
                .fillna(0)
                .round(3))
    if df_chart.shape[0] == 0:
        return None
    df_chart.rename(columns={
        "CampaignID": u"Кампания №",
        "CampaignName": u"Название кампании",
        "DirectBannerID": u"Баннер №",
        "PhraseText": u"Ключевая фраза",
        "AvgPosShowsOther": u"Ср. поз. показов (юж./пр. блок)",
        "ShowsOther": u"Показы (юж./пр. блок)",
        "ShowsSpec": u"Показы (спец)",
        "CPC_other": u"CPC (юж./пр. блок)",
        "CPC_spec": u"CPC (спец)",
        "CTR_other": u"CTR (юж./пр. блок)",
        "CTR_spec": u"CTR (спец.)"},
        inplace=True)

    return df_chart


def table_top_cpc_phrases(df):
    """13_top_cpc_phrases"""

    df_chart = (df[["DirectBannerID", "PhraseText", "Shows", "Clicks", "Cost"]]
                .groupby(["DirectBannerID", "PhraseText"], as_index=False)
                .sum()
                .assign(CPC=lambda x: x.Cost / x.Clicks)
                .assign(CTR=lambda x: x.Clicks / x.Shows)
                .fillna(0)
                .sort_values("CPC", ascending=False)
                .reset_index(drop=True)
                .head(EXCEL_MAX_ROWS))

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

    df_chart.rename(columns={
        "DirectBannerID": u"Баннер №",
        "PhraseText": u"Ключевая фраза",
        "Shows": u"Показы",
        "Clicks": u"Клики",
        "Cost": u"Затраты",
        "CPC": u"CPC",
        "CTR": u"CTR"},
        inplace=True)

    return df_chart.loc[:, [u"Баннер №",
                            u"Ключевая фраза",
                            u"Показы",
                            u"Клики",
                            u"Затраты",
                            u"CPC",
                            u"CTR"]]
