# -*- coding: utf-8 -*-
from datetime import datetime, timedelta
import logging
from os.path import dirname, join
from cpa_data_task.utils import round_date
from make_data import DICTS
from exceller import ExcelDocument

logger = logging.getLogger(__name__)


def make_data_xlsx(cpa_task):
    data_path = join(dirname(dirname(__file__)), '{}_data.xlsx').format(cpa_task.issue.key)
    wb = ExcelDocument(join(dirname(__file__), 'templates', DICTS['task_template']))
    wb = clean_template(wb)

    info_ws = wb['Info']
    if cpa_task.type_ == 'standard':
        info_ws['B9'].text = u'Да' if cpa_task.categorization['use_domain_sets'] else u'Нет'
    else:
        info_ws['B9'].text = '-'
    info_ws['B14'].text = u'Да' if cpa_task.separate_data else u'Нет'

    info_ws['B20'].text = cpa_task.time_detail
    info_ws['B25'].text = cpa_task.period['first_date']
    info_ws['D25'].text = round_date(datetime.strptime(cpa_task.period['last_date'], '%Y-%m-%d') + timedelta(days=-1),
                                     cpa_task.time_detail).strftime('%Y-%m-%d')

    info_ws['B31'].text = cpa_task.attribution
    info_ws['B36'].text = u'руб.' if cpa_task.currency == u'рубль' else cpa_task.currency
    info_ws['B41'].text = u'Да' if cpa_task.vat else u'Нет'

    info_ws.set_cell_hyperlink(47, 2, 'https://st.yandex-team.ru/{}'.format(cpa_task.issue.key), cpa_task.issue.key)

    write_df(info_ws, cpa_task.data_included, from_col=13)
    write_df(wb['Data'], cpa_task.result_df)

    wb.save(data_path)

    return data_path


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


def clean_template(wb):
    info_ws = wb['Info']
    for row in [9, 14, 20, 25, 31, 36, 41, 47]:
        info_ws.clear_value('B{row}:E{row}'.format(row=row))
    info_ws.clear_value('M1:S%i' % get_last_cell(info_ws, column=13).row.row_index)

    data_ws = wb['Data']
    data_ws.clear_value('A1:X%i' % get_last_cell(data_ws, column=1).row.row_index)

    return wb


def get_last_cell(ws, from_row=1, column=1):
    last_cell = None

    row = from_row
    while ws.rows.get(row):
        if ws.rows[row].get_cell(column).text:
            last_cell = ws.rows[row].get_cell(column)
            row += 1
        else:
            break

    return last_cell
