# -*- coding: utf-8 -*-
from datetime import datetime
import logging
from os import getcwd
from os.path import join
from exceller import ExcelDocument

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

logger = logging.getLogger(__name__)


def run_data_workers():
    try:
        period = get_period()
        fill_xlsx_template({
            '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': get_potential(),
            'one_cent_clicks': one_cent_clicks(period),
            'channels': yql_worker('channels', period),
            'promocodes': yql_worker('promocodes', period),
            'new_goals': yql_worker('new_goals', period),
            'stopped_clients': yql_worker('stopped_clients', period),
            'free_settings': yql_worker('free_settings', period),
            'mobile_apps': yql_worker('mobile_apps', period),
            'appanie': yql_worker('appanie', period),
            'funnel': get_funnel_table(),
            'new_interface': yql_worker('new_interface', 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)
        })
    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.iteritems():
        wb[ws_name].clear_value('A1:AA15000')

    for ws_name, df in dfs.iteritems():
        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 xrange(len(df.index)):
            ws.set_cell_value(from_row + 1 + row_num, col_num, df[col_name][row_num])

    return ws
