# -*- coding: utf-8 -*-
#!/usr/bin/env python3
from datetime import datetime
import logging
from os import getcwd
from os.path import join
from exceller import ExcelDocument

from client_analytics.weekly_pack_py3.weekly_pack.data.artmon_worker import april_data, one_cent_clicks
from client_analytics.weekly_pack_py3.weekly_pack.data.proceed_data import get_period
from client_analytics.weekly_pack_py3.weekly_pack.data.stat_workers import get_shares, get_clusters, get_potential
from client_analytics.weekly_pack_py3.weekly_pack.data.yql_workers import yql_worker, get_funnel_table, get_telephony_data
from client_analytics.weekly_pack_py3.weekly_pack.utils import get_file

logger = logging.getLogger(__name__)


def run_data_workers():
    try:
        period = get_period()
        fill_xlsx_template({
            'Cnt_SPI_Ad': yql_worker('Cnt_SPI_Ad', period),
            'Cashback_by_Product': yql_worker('Cashback_by_Product', period),
            'Cashback_Funnel': yql_worker('Cashback_Funnel', period),
            'Ecom_Funnel': yql_worker('Ecom_Funnel', period),
            'Ecom_Share': yql_worker('Ecom_Share', period),
            'InApp_Rev': yql_worker('InApp_Rev', period),
            'SOC_Share': yql_worker('SOC_Share', period),
            'Traffic_Coverage_by_Metrica': yql_worker('Traffic_Coverage_by_Metrica', period),
            'Agencies_Reward': yql_worker('Agencies_Reward', period),
            'Tac_Rate': yql_worker('Tac_Rate', period),
            'SMB_Share': yql_worker('SMB_Share', period),
            'SMB_Clients_Share_by_Avg_Cheque': yql_worker('SMB_Clients_Share_by_Avg_Cheque', period),
            'Campaign_Master_Share': yql_worker('Campaign_Master_Share', period),
            'Time_to_Target_to_Show_SMB': yql_worker('Time_to_Target_to_Show_SMB', period),
            'Time_to_Target_to_Click_SMB': yql_worker('Time_to_Target_to_Click_SMB', period),
            'Clients_Interface_EvaluationSMB': yql_worker('Clients_Interface_EvaluationSMB', period),
            'metrika_spending_import': yql_worker('metrika_spending_import', period),
            'agency_revenue': yql_worker('agency_revenue', period),
            'Share_of_Companies_wo_Convers': yql_worker('Share_of_Companies_wo_Convers', period),
            'Survival_Rate': yql_worker('Survival_Rate', period),
            'Time_to_Target': yql_worker('Time_to_Target', period),
            'Rev_Share': yql_worker('Rev_Share', period),
            'Interface_Share_by_Client': yql_worker('Interface_Share_by_Client', period),
            'Network_Rev_by_Geo': yql_worker('Network_Rev_by_Geo', period),
            'Rev_by_Place_2': yql_worker('Rev_by_Place_2', period),
            'ecom_retargeting_costs': yql_worker('ecom_retargeting_costs', period),
            'ecom_retargeting_clientid': yql_worker('ecom_retargeting_clientid', period),
            'nps_direct': yql_worker('nps_direct', period),
            'time2target': yql_worker('time2target', period),
            'moderation_sla': yql_worker('moderation_sla', period),
            'new_camp_smb': yql_worker('new_camp_smb', period),
            'plan_fact_tiers': yql_worker('plan_fact_tiers', period),
            'artmon': april_data(period),
            'status': yql_worker('status', period),
            'other': yql_worker('cost', period),
            'runtime': yql_worker('runtime', period),
            'conversions': yql_worker('conversions', period),
            'potential': yql_worker('potential', period),
            'one_cent_clicks': one_cent_clicks(period),
            'channels': yql_worker('channels', period),
            'promocodes': yql_worker('promocodes', period),
            'mobile_apps': yql_worker('mobile_apps', period),
            #'moderation_speed': yql_worker('moderation', period),
            #'moderation_precision': yql_worker('moderation_precision', period),
            'client_care': yql_worker('client_care', period),
            'searches_new': yql_worker('searches_new', period),
            'ad_visits': yql_worker('ad_visits', period),
            #'penetration_ads': yql_worker('penetration_ads', period),
            'k50_aum': yql_worker('k50_aum', period),
            'clients_budget': yql_worker('clients_budget', period),
            'conversion_share': yql_worker('conversion_share', period),
            'ecom': yql_worker('ecom', period),
            'regions': yql_worker('regions', period),
            'media_video': yql_worker('media_video', period),
            'yan': yql_worker('yan', period),
        })
    except:
        logger.exception('Oops!')
    return


def fill_xlsx_template(dfs):
    wb = ExcelDocument(get_file('templates', 'wp_data_v0.1.xlsx'))
    for ws_name, df in dfs.items():
        wb[ws_name].clear_value('A1:AA15000')

    for ws_name, df in dfs.items():
        if isinstance(df, list):
            for table in df:
                write_df(wb[ws_name], table.fillna(''), from_row=table.from_row, from_col=table.from_col)
        else:
            write_df(wb[ws_name], df.fillna(''))

    wb.save(join(getcwd(), 'wp_data_{:%Y-%m-%d %H-%M-%S}.xlsx'.format(datetime.now())))

    return



def write_df(ws, df, fill_header=True, from_row=1, from_col=1):
    for col_num, col_name in enumerate(df.columns, from_col):
        if fill_header:
            ws.set_cell_value(from_row, col_num, col_name)

        for row_num in range(len(df.index)):
            ws.set_cell_value(from_row + 1 + row_num, col_num, df[col_name][row_num])

    return ws
