# coding: utf-8
"""xlsx-mobile:
  - 08_img_shapes
  - 09_rsya_banners_wo_img
"""
from ..const import EXCEL_MAX_ROWS, TMP_DIR_PATH
from ..utils import get_image_shape, get_max_images
from .utils import (
    add_cpc_rsya,
    add_ctr_rsya
)
from os.path import isfile, join as pjoin
from multiprocessing.dummy import Pool
import pandas as pd
import logging


def fetch_img_shapes(df):
    """(DataFrame) -> DataFrame?
    08_img_shapes
    """
    get_max_images()
    storage_path = pjoin(TMP_DIR_PATH, "img_shapes_rmp.pkl")
    if not isfile(storage_path):
        img_shapes = df[df.ImageHash != 'None'].ImageHash.unique()
        if 0 < img_shapes.size <= get_max_images():
            logging.info("...%s images are downloading" % img_shapes.size)
            img_shapes = Pool(4).map(get_image_shape, img_shapes, 10)
            img_shapes = pd.DataFrame([{
                "ImageHash": k[0],
                "height": k[1],
                "width": k[2]
            } for k in img_shapes])
            img_shapes.to_pickle(storage_path)
            logging.info("...dowload %s images" % img_shapes.shape[0])
        else:
            if img_shapes.size == 0:
                logging.warn("there are no images: %s" % img_shapes.size)
            if img_shapes.size > get_max_images():
                logging.warn("too many images: %s. Current `IMG_MAX_DOWNLOAD` is: %s" %
                             (img_shapes.size, get_max_images()))
            img_shapes = None
    else:
        img_shapes = pd.read_pickle(storage_path)
        logging.info(
            "...load %s images from %s" % (img_shapes.shape[0], storage_path))

    return img_shapes


def chart_table_img_shapes(df, img_shapes):
    """
    (DataFrame, DataFrame?) -> DataFrame?
    08_img_shapes
    """

    if img_shapes is None:
        return None

    df_chart = df[[
        "ShowsRSYA", "ClicksRSYA", "CostRSYA", "ImageHash", "DirectBannerID"
    ]].copy()
    df_chart = pd.merge(df_chart, img_shapes.drop_duplicates(), on="ImageHash")
    df_chart = (df_chart[df_chart.ShowsRSYA > 0]
                .groupby(["ImageHash", "height", "width", "DirectBannerID"], as_index=False)
                .agg({
                    "ShowsRSYA": pd.np.sum,
                    "ClicksRSYA": pd.np.sum,
                    "CostRSYA": pd.np.sum
                }))
    df_chart.sort_values("ShowsRSYA", ascending=False, inplace=True)

    return df_chart


# todo(n-bar) add normalize as an option
def table_img_shapes(df):
    """08_img_shapes"""
    # todo(n-bar) delete fetch_img_shapes and use special columns
    img_shapes = fetch_img_shapes(df)
    df_chart = chart_table_img_shapes(df, img_shapes)
    if df_chart is None:
        return None

    df_chart = (df_chart[df_chart.ShowsRSYA > 0]
                .groupby(["height", "width"], as_index=False)
                .agg({
                    "ShowsRSYA": pd.np.sum,
                    "ClicksRSYA": pd.np.sum,
                    "CostRSYA": pd.np.sum,
                    "DirectBannerID": lambda x: x.unique().size,
                    "ImageHash": lambda x: x.unique().size
                })
                .rename(columns={
                    "ImageHash": "UniqImgCnt",
                    "DirectBannerID": "BannersCnt"
                })
                .assign(area=lambda x: x.height * x.width)
                .sort_values("area")
                .reset_index(drop=True)
                .drop("area", axis=1))

    add_cpc_rsya(df_chart)
    add_ctr_rsya(df_chart)

    df_chart.rename(columns={
        "height": u"Высота",
        "width": u"Ширина",
        "ShowsRSYA": u"Показы (сети)",
        "ClicksRSYA": u"Клики (сети)",
        "CostRSYA": u"Затраты (сети)",
        "CPCRSYA": u"CPC (сети)",
        "CTRRSYA": u"CTR (сети)",
        "UniqImgCnt": u"Кол-во разных картинок",
        "BannersCnt": u"Кол-во баннеров"
    }, inplace=True)

    return df_chart.loc[:, [u"Высота",
                            u"Ширина",
                            u"Показы (сети)",
                            u"Клики (сети)",
                            u"Затраты (сети)",
                            u"CPC (сети)",
                            u"CTR (сети)",
                            u"Кол-во разных картинок",
                            u"Кол-во баннеров"]]


def table_rsya_banners_wo_img(df):
    """09_rsya_banners_wo_img"""

    df_chart = (df[(df.ImageHash == 'None') &
                   (df.ShowsRSYA > 0)]
                .loc[:, ["CampaignID", "CampaignName", "DirectBannerID",
                         "Title", "Body",
                         "ShowsRSYA", "ClicksRSYA", "CostRSYA"]]
                .groupby(["CampaignID", "CampaignName", "DirectBannerID", "Title", "Body"])
                .agg({
                    "ShowsRSYA": pd.np.sum,
                    "ClicksRSYA": pd.np.sum,
                    "CostRSYA": pd.np.sum})
                .sort_values("ShowsRSYA", ascending=False)
                .head(EXCEL_MAX_ROWS))

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

    add_cpc_rsya(df_chart)
    add_ctr_rsya(df_chart)

    df_chart.rename(
        columns={
            "ShowsRSYA": u"Показы (сети)",
            "ClicksRSYA": u"Клики (сети)",
            "CostRSYA": u"Затраты (сети)",
            "CPCRSYA": u"CPC (сети)",
            "CTRRSYA": u"CTR (сети)"
        }, inplace=True)
    df_chart.index.names = [
        u"Кампания №", u"Название кампании", u"Баннер №", u"Заголовок", u"Объявление"
    ]
    return df_chart.loc[:, [u"Показы (сети)",
                            u"Клики (сети)",
                            u"Затраты (сети)",
                            u"CPC (сети)",
                            u"CTR (сети)"]]
