# -*- coding: utf-8 -*-
from os import remove
from os.path import basename, dirname, join
from zipfile import ZipFile
from datetime import datetime as dt
from datetime import timedelta


def proceed_form_value(form_value, default=None):
    form_value = None if form_value in [None, 'None', ''] else form_value.strip()
    if not form_value and default:
        return default
    else:
        if form_value == u'Yes':
            form_value = u'Да'
        elif form_value == u'No':
            form_value = u'Нет'
        return form_value


def convert_name(name, names, to_local=True):
    """
    :param name: значение параметра из формы на русском (Поиск, Десктоп, ДРР e.t.) / как в данных
    :param names: словарь из файла names.yml
    :param to_local: True/False
    if to_local
        :return: ключ, соответствующий названию из формы (Поиск -> Search)
    else
        значение, соответствующее name (Поиск -> Search)
    """
    if to_local:
        for k, v in names.iteritems():
            if v == name:
                return k

    else:
        return names.get(name, name)

    return name


def get_data_filters(filters, f_type):
    """
    :param filters: строка с разделителем-запятой
    :param f_type: колонка для перевода
    """
    assert f_type in ['Place', 'Device', 'Category'], 'unknown f_type: %s' % f_type
    if not filters:
        return []

    return [filter_.strip() for filter_ in filters.split(',')]


def get_datetime_period(time_detail, period):
    if not proceed_form_value(period):
        return None

    first_date, last_date = [dt.strptime(date.strip(), '%Y-%m-%d') for date in period.split(' - ')]
    return {
        'first_date': round_date(first_date, time_detail),
        'last_date': round_date(last_date, time_detail)
    }


def round_date(date, time_detail):
    if time_detail == u'Дни':
        return date

    elif time_detail == u'Недели':
        return date - timedelta(days=date.weekday())

    elif time_detail == u'Месяцы':
        return dt(year=date.year, month=date.month, day=1)


def overlapping_periods(period_1, period_2):
    if period_1['first_date'] <= period_2['first_date'] and period_1['last_date'] >= period_2['first_date']:
        return True
    else:
        return False


def equal_periods(period_1, period_2):
    if period_1['first_date'] == period_2['first_date'] and period_1['last_date'] == period_2['last_date']:
        return True
    else:
        return False


def get_competitors(competitors):
    if not competitors:
        return None

    return [comp.strip() for comp in competitors.split('\n') if comp.strip()]


def replace_target_metric(calculations, target):
    for k, val in calculations.iteritems():
        if k == 'format' or type(val) == bool:
            continue
        if type(val) == dict:
            replace_target_metric(val, target)
        else:
            calculations[k] = val.format(target_metric=target)

    return calculations


def zip_reports(files, arc_name):
    arc_path = join(dirname(dirname(__file__)), arc_name)
    zip_file = ZipFile(arc_path, 'w')
    for file_ in files:
        zip_file.write(file_, arcname=basename(file_))
        remove(file_)

    zip_file.close()

    return arc_path
