# -*- coding: utf-8 -*-
from datetime import datetime
from datetime import timedelta
from dateutil.relativedelta import relativedelta
from cpa_data_task import TASK_TYPES


def get_task_type(type_name):
    for type_, name in TASK_TYPES.iteritems():
        if name == type_name:
            return type_
    return None


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:
        return form_value


def get_period(time_detail, period):
    if not period:
        return None

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


def round_date(date, time_detail, to_end=False):
    if time_detail == u'Дни':
        if to_end:
            return date + relativedelta(days=1)
        else:
            return date

    elif time_detail == u'Недели':
        monday = date - timedelta(days=date.weekday())
        if to_end:
            return monday + relativedelta(days=7)
        else:
            return monday

    elif time_detail == u'Месяцы':
        if to_end:
            return datetime(date.year, date.month, 1) + relativedelta(months=1)
        else:
            return datetime(year=date.year, month=date.month, day=1)


def get_date_func(time_detail):
    if time_detail == u'Дни':
        return 'toDate'

    elif time_detail == u'Недели':
        return 'toMonday'

    elif time_detail == u'Месяцы':
        return 'toStartOfMonth'


def bad_value(value):
    if isinstance(value, int) or isinstance(value, float):
        value = str(int(value))

    bad_chars = [
        char for char in value.encode('utf-8').strip() if not char.isdigit() and char not in ['', ',', ' ', '\n']
    ]
    if bad_chars:
        return True
    else:
        return False


def parse_list(str_list):
    if isinstance(str_list, int) or isinstance(str_list, float):
        str_list = str(int(str_list))

    new_list = [elem.strip() for elem in str_list.split(',') if elem.strip()]

    new_list = list(set(new_list))
    new_list.sort()
    return u', '.join(new_list)


def get_list_from_tf(text_field):
    if isinstance(text_field, int) or isinstance(text_field, float):
        text_field = str(int(text_field))

    new_list = [val.strip() for val in text_field.split('\n') if val.strip()]
    new_list = [parse_list(val) for val in new_list]

    return new_list if new_list else [u'']


def get_attribution_prefix(attribution):
    if attribution == u'Первый переход':
        return attribution, 'FirstTraficSource'

    elif attribution == u'Последний переход':
        return attribution, ''

    elif attribution == u'Последний значимый переход':
        return attribution, 'LastSignificantTraficSource'


def get_cur_coef(currency):
    if currency == u'рубль':
        cur_coef = 1.

    elif currency == u'y.e.':
        cur_coef = 1 / 30.

    else:
        cur_coef = 0

    return cur_coef


def decode_cell(cell):
    if isinstance(cell, (int, unicode)) or cell is None:
        return cell
    else:
        return cell.decode('utf-8')
