# coding: utf-8
import pandas as pd
from ..utils import get_all_campaigns, review_search_queries_url


def table_logins_overview(df, show_total=False):
    """00_logins_overview"""

    df_chart = df.copy().fillna(0)

    camp_df = (df_chart.copy()[["Login", "CampaignID"]]
               .drop_duplicates().dropna()
               .set_index(["Login"]))

    group_cols = ["Login"]
    df_chart = (df_chart
                .groupby(group_cols + ["DateBegin", "DateFinish"], as_index=False)
                .agg({"Shows": pd.np.sum, "Clicks": pd.np.sum, "Cost": pd.np.sum
                      })
                )

    df_chart["Campaigns"] = df_chart.apply(lambda row: get_all_campaigns(row, camp_df), axis=1)
    df_chart["Url"] = df_chart.apply(lambda row: review_search_queries_url(row), axis=1)

    group_cols.append("Url")
    df_chart = (df_chart.groupby(group_cols, as_index=False).sum())

    if show_total:
        df_chart = pd.DataFrame(df_chart.sum(axis=0, numeric_only=True)).T
        for col in ["Login", "Url"]:
            df_chart[col] = ""

    df_chart = df_chart[["Login", "Url", "Shows", "Clicks", "Cost"]]
    cols = {
        "Login": u"Логин",
        "Url": u"Ссылка на кампании",
        "Shows": u"Показы",
        "Clicks": u"Клики",
        "Cost": u"Расходы"
    }
    for col in df_chart.columns:
        df_chart.rename(columns={col: cols.get(col, col)}, inplace=True)

    setattr(df_chart, "formats", {u"Логин": "string",
                                  u"Ссылка на кампании": "hyperlink",
                                  u"Показы": "int",
                                  u"Клики": "int",
                                  u"Расходы": "float"})

    return df_chart
