# -*- coding: utf-8 -*-
import logging
import xlrd
from camp_builder import CONFIG
from errs import GeoError
from geo_worker import get_geobase
from utils import get_geo_kwargs, format_user_keys, mixed_geo, read_ws

logger = logging.getLogger(__name__)


def read_standart_task(task_path):
    geo_list = fill_geobase(
        read_ws(task_path, u'Кампании', range(5),
                {u'Гео': 'Geo', u'Ссылка': 'Url', u'Изображение': 'ImageUrl', u'Код': 'Code'},
                skiprows=1)
    )

    return {'geo_list': geo_list}


def read_direction_task(task_path, options):
    origins = fill_geobase(
        read_ws(task_path, u'Гео', range(2), {u'Гео отправления': 'Geo', u'Изображение': 'ImageUrl'}, skiprows=1)
    )
    destinations = fill_geobase(
        read_ws(task_path, u'Гео', range(3, 5), {u'Гео назначения': 'Geo', u'Изображение': 'ImageUrl'}, skiprows=1),
        is_dest=True
    )
    locations = []
    for dest in destinations:
        location = dest.copy()
        location['Url'] = options['DestUrl']
        locations.append(location)

    for origin in origins:
        if all([origin['Geo'] != dest['Geo'] for dest in destinations]):
            location = origin.copy()
            location['Url'] = options['OriginUrl']
            locations.append(location)

    if options['group_by'] == 'origin':
        geo_list = mixed_geo(origins, destinations)
    else:
        geo_list = mixed_geo(destinations, origins)

    codes = read_ws(task_path, u'Гео', range(8, 10), {u'Гео': 'Geo', u'Код': 'Code'}, skiprows=1)
    codes = {code['Geo']: code['Code'] for code in codes}

    return {'geo_list': geo_list, 'origins': origins, 'destinations': destinations, 'locations': locations,
            'codes': codes}


def fill_geobase(geo_list, is_dest=False):
    bad_geo = []
    for geo_dict in geo_list:
        try:
            geo_dict['geobase'] = get_geobase(geo_dict['Geo'])
            geo_dict['kwargs'] = get_geo_kwargs(geo_dict['geobase'], is_dest)  # падежи

        except Exception as exc:
            logger.error(u'{}: {}'.format(geo_dict['Geo'], exc.message))
            if isinstance(geo_dict['Geo'], (int, float)):
                bad_geo.append(str(geo_dict['Geo']))
            else:
                bad_geo.append(geo_dict['Geo'])

    if bad_geo:
        raise GeoError(
            u'Некоторые гео не удалось достать из геобазы (https://geoadmin.yandex-team.ru):\n{}\n\n'
            u'Попробуйте указать их через GeoID.'.format(u'\n'.join(bad_geo))
        )
    return geo_list


def get_camp_options(task_path):
    wb = xlrd.open_workbook(task_path)

    ws = wb.sheet_by_name(u'Настройки')
    category = ws.cell(1, 1).value
    loc_cat = CONFIG['local_categories'].get(category, 'other')

    options = {
        'local_category': loc_cat,

        'camp_title_template': ws.cell(3, 1).value.replace(u'гео', u'geo'),
        'camp_lang': 'en' if ws.cell(4, 1).value == u'английский' else 'ru',
        'group_title_template': ws.cell(5, 1).value.replace(u'гео', u'geo'),
        'group_lang': 'en' if ws.cell(6, 1).value == u'английский' else 'ru',

        'bid': float(ws.cell(10, 1).value),
        'сallouts': ws.cell(11, 1).value,
        'negative_keywords': ws.cell(12, 1).value,

        'ads': get_ads(task_path),
        'groups': get_groups(task_path)
    }

    if loc_cat == 'tickets':
        ws = wb.sheet_by_name(u'Ссылки')

        if ws.cell(1, 1).value == u'по гео отправления':
            options['group_by'] = 'origin'
        elif ws.cell(1, 1).value == u'по гео назначения':
            options['group_by'] = 'destination'

        options['Url'] = ws.cell(3, 1).value
        options['OriginUrl'] = ws.cell(4, 1).value
        options['DestUrl'] = ws.cell(5, 1).value

    else:
        ws = wb.sheet_by_name(u'Кампании')
        try:
            options['Url'] = ws.cell(1, 8).value
        except IndexError:
            options['Url'] = u''

    sitelinks = read_ws(task_path, u'Настройки', range(9, 12),
                        {u'Заголовок': 'Title', u'Ссылка': 'Sitelink', u'Описание': 'Text'}, skiprows=11)
    sitelinks = format_user_keys(sitelinks, ['Title', 'Text'])
    options['sitelinks'] = sitelinks

    return options


def get_extra_negative_keywords(camp_name, params, options):
    if camp_name == 'Origins':
        geo_list = params['destinations']
    elif camp_name == 'Destinations':
        geo_list = params['origins']
    else:
        geo_list = params['locations']

    extra_kw = u', '.join([geo_dict['geobase']['Runame'] for geo_dict in geo_list])
    if camp_name == 'Locations':
        extra_kw = u'!из, !в, {}'.format(extra_kw)

    return u', '.join([extra_kw, options['negative_keywords']])


def get_ads(task_path):
    ads = read_ws(
        task_path, u'Настройки', range(5, 8), {u'Заголовок 1': 'Title1', u'Заголовок 2': 'Title2', u'Текст': 'Text'},
        skiprows=11)
    ads = format_user_keys(ads, ['Title1', 'Title2', 'Text'])

    return ads


def get_groups(task_path):
    phrases = read_ws(task_path, u'Группы', range(3), {u'№ группы': 'GroupID', u'Фраза': 'Phrase'})

    group_names = {}
    group_names_list = read_ws(task_path, u'Группы', range(8, 10),
                               {u'№ группы': 'GroupID', u'Маска названия группы': 'GroupName'})
    for row in group_names_list:
        group_names[row['GroupID']] = {'GroupName': row['GroupName'].replace(u'гео', 'geo')}

    groups = {}
    for phrase in phrases:
        if groups.get(phrase['GroupID']):
            groups[phrase['GroupID']]['Phrases'].append(phrase['Phrase'])
        else:
            groups[phrase['GroupID']] = {'Phrases': [phrase['Phrase'], ]}
            if group_names.get(phrase['GroupID']):
                groups[phrase['GroupID']]['GroupName'] = group_names[phrase['GroupID']]['GroupName']

    return groups
