# coding: utf-8
"""xlsx-keywords:
  - 10_avg_time_target
  - 10_use_time_target_campaigns

Help:
[Hourly CPC adjustment]
  (https://yandex.ru/support/direct/features/hourly-cpc-adjustment.xml?lang=en)
[Time targeting]
  (https://yandex.ru/support/direct/efficiency/timetargeting.xml?lang=en)
"""
from ..review import Recommendation, append_recommendation
from ..utils import extract_timetarget
from .utils import (
    add_cpc_total,
    add_ctr_total
)
import pandas as pd


def table_avg_time_target(df):
    """10_avg_time_target"""

    df_chart = (df[["CampaignID", "CampaignName", "TimeTarget", "Shows"]]
                .groupby(["CampaignID", "CampaignName", "TimeTarget"], as_index=False)
                .sum()
                .assign(TimeTarget=lambda x: x.TimeTarget.apply(extract_timetarget)))
    df_chart = ((df_chart.TimeTarget.sum() / df_chart.shape[0])
                .round(2)
                .rename(columns={0: u" День №"}))

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

    if (df_chart.drop([u" День №", ], axis=1) < 100).any().any():
        # Пороги из головы экперта, можно крутить
        Rec = Recommendation(
            dataframe=df,
            internal_sheet_name="10_avg_time_target",
            title=u"Временной таргетинг",
            snippet=u"Настройки временного таргетинга могут сужать охват аудитории",
            importance_lvl=2)
        append_recommendation(df, Rec)

    return df_chart


def use_time_target_campaigns(df):
    """10_use_time_target_campaigns"""

    use_adjustment = lambda tt_cell: pd.np.concatenate(tt_cell.loc[:, 1:].values != 100).any()
    avg_adjustment = lambda tt_cell: pd.np.concatenate(tt_cell.loc[:, 1:].values).mean()

    df_chart = (df[["CampaignID", "CampaignName", "TimeTarget", "Shows", "Clicks", "Cost"]]
                .groupby(["CampaignID", "CampaignName", "TimeTarget"], as_index=False)
                .sum()
                .assign(TimeTarget=lambda x: x.TimeTarget.apply(extract_timetarget))
                .assign(use_adjustment=lambda x: x.TimeTarget.apply(use_adjustment))
                .assign(avg_adjustment=lambda x: x.TimeTarget.apply(avg_adjustment))
                .pipe(lambda df: df.loc[df.use_adjustment])
                .drop(["TimeTarget", "use_adjustment"], axis=1)
                .sort_values("CampaignID")
                .reset_index(drop=True))

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

    add_cpc_total(df_chart)
    add_ctr_total(df_chart)

    df_chart.rename(columns={
        "CampaignID": u"Кампания №",
        "CampaignName": u"Название кампании",
        "avg_adjustment": u"Средняя корректировка",
        "Shows": u"Показы",
        "Clicks": u"Клики",
        "Cost": u"Затраты",
        "CPC": u"CPC",
        "CTR": u"CTR"},
        inplace=True)

    df_chart = df_chart.loc[:, [u"Кампания №", u"Название кампании", u"Средняя корректировка",
                                u"Показы", u"Клики", u"Затраты", u"CPC", u"CTR"]]

    setattr(df_chart, "formats", {u"Кампания №": "string",
                                  u"Название кампании": "string",
                                  u"Средняя корректировка": "float",
                                  u"Показы": "int",
                                  u"Клики": "int",
                                  u"Затраты": "float",
                                  u"CPC": "float",
                                  u"CTR": "percent"})

    return df_chart
