# -*- coding: utf-8 -*-
import logging
import traceback as tb
from camp_builder import CONFIG
from errs import GroupError, TemplateError

logger = logging.getLogger(__name__)


def get_group_name(title_template, geobase, lang):
    try:
        if lang == 'ru':
            return title_template.format(geo=geobase['Runame'])
        elif lang == 'en':
            return title_template.format(geo=geobase['Enname'])

    except KeyError:
        raise TemplateError(u'Неизвестные ключевые слова в заголовке групп объявлений {}:\n{}\n'.format(
            title_template, tb.format_exc()
        ), where='group_title')

    except Exception as exc:
        raise exc


def get_url(template, **kwargs):
    try:
        return template.format(**kwargs).replace(' ', '-')
    except KeyError:
        raise TemplateError(u'Неизвестные ключевые слова в ссылке {}:\n{}\n'.format(template, tb.format_exc()),
                            where='url')
    except Exception as exc:
        raise exc


def get_location(origin_geobase, dest_geobase, lang, group_by=None):
    dirs = []
    if lang == 'en':
        if origin_geobase:
            preposition = u'from' if group_by else u'in'
            dirs.append(u'{} {}'.format(preposition, origin_geobase['Enname']))

        if dest_geobase:
            dirs.append(u'to {}'.format(dest_geobase['Enname']))

    elif lang == 'ru':
        if origin_geobase:
            if group_by:
                preposition, case_key = u'из', 'RunameGenitive'
            else:
                preposition, case_key = origin_geobase['RunamePreposition'], 'RunamePrepositional'
            dirs.append(u'{} {}'.format(preposition, origin_geobase[case_key]))

        if dest_geobase:
            dirs.append(u'в {}'.format(dest_geobase['RunameAccusative']))

    return u' '.join(dir_ for dir_ in dirs if dir_)


def get_geo_sitelinks(geo, sitelinks_list):
    sitelinks = {'Titles': [], 'Sitelinks': [], 'Texts': []}

    for sitelink in sitelinks_list:
        if not sitelink.get('Geo') or sitelink.get('Geo') == geo:
            sitelinks['Titles'].append(sitelink['Title'])
            sitelinks['Sitelinks'].append(sitelink['Sitelink'])
            sitelinks['Texts'].append(sitelink['Text'])

    for k, v in sitelinks.iteritems():
        sitelinks[k] = u'||'.join(v)

    return sitelinks


def format_sitelinks(sitelinks, geo_kwargs, utm=None):
    for k in ['Titles', 'Texts']:
        try:
            sitelinks[k] = sitelinks[k].format(**geo_kwargs)
        except KeyError:
            raise TemplateError(u'Неизвестные ключевые слова в {} БС {}:\n{}\n'.format(
                u'заголовке' if k == 'Titles' else u'описании', sitelinks[k], tb.format_exc()
            ), where='sitelinks_title' if k == 'Titles' else 'sitelinks_text')

        except Exception as exc:
            raise exc

    if utm:
        try:
            sitelinks['Sitelinks'] = sitelinks['Sitelinks'].format(**utm).replace(' ', '-')
        except KeyError:
            raise TemplateError(
                u'Неизвестные ключевые слова в БС {}:\n{}'.format(sitelinks['Sitelinks'], tb.format_exc()),
                where='sitelinks'
            )
        except Exception as exc:
            raise exc

    return sitelinks


def format_ads(ads_list, geo_kwargs):
    formatted_ads = []
    for ad_template in ads_list:
        ad = {}
        for k, v in ad_template.iteritems():
            try:
                ad[k] = ad_template[k].format(**geo_kwargs)
            except KeyError:
                raise TemplateError(
                    u'Неизвестные ключевые слова в объявлениях {}:\n{}\n'.format(ad_template[k], tb.format_exc()),
                    where='ad_%s' % k
                )
            except Exception as exc:
                raise exc

        formatted_ads.append(ad)

    return formatted_ads


def fix_base_ad(base_ad, extra_ads):
    for key in ['Title1', 'Title2', 'Text']:
        if not is_good_ad(base_ad, key):

            for extra_ad in extra_ads:
                base_ad[key] = extra_ad[key]
                if is_good_ad(base_ad, key):
                    break

    if not is_good_ad(base_ad):
        raise GroupError(u'Не хватает шаблонов объявлений на листе «Настройки»!')

    return base_ad


def build_extra_ads(extra_ads, template, **kwargs):
    ads = []
    for extra_ad in extra_ads:
        ad = template.copy()
        for k, v in kwargs.iteritems():
            ad[k] = v

        ad['IsExtra'] = u'+'

        ad['Title1'] = extra_ad['Title1']
        ad['Title2'] = extra_ad['Title2']
        ad['Text'] = extra_ad['Text']

        ad['Bid'] = None
        ad['NegativeKeywords'] = None

        if is_good_ad(ad):
            ads.append(ad)

    return ads


def is_good_ad(ad, key=None):
    if not key:
        for key in ['Title1', 'Title2', 'Text']:
            if 'None' in ad[key] or len(get_clean_text(ad[key])) > CONFIG['lens'][key]:
                return False

    else:
        if 'None' in ad[key] or len(get_clean_text(ad[key])) > CONFIG['lens'][key]:
            return False

    return True


def get_clean_text(text):
    for mark in ['.', ',', ':', ';', '!', '#']:
        text = text.replace(mark, '')
    return text.strip()


def get_phrase(phrase, location):
    if phrase.find(' -') != -1:
        negative_keywords = phrase[phrase.find(' -'):].strip()
        phrase = phrase[:phrase.find(' -')].strip()
    else:
        negative_keywords, phrase = None, phrase

    idx = None
    for idx, char in enumerate(reversed(phrase.split(u' ')[-1])):
        if char.isalnum():
            break

    if idx in [None, 0]:
        new_phrase = u'{} {}'.format(phrase, location)
    else:
        new_phrase = u'{} {}{}'.format(phrase[:-idx], location, phrase[-idx:])

    if negative_keywords:
        return u'{} {}'.format(new_phrase, negative_keywords)
    else:
        return new_phrase


def get_title_by_phrase(phrase, title):
    for char in ['[', ']', '+']:
        phrase = phrase.replace(char, '')

    if len(phrase) <= 35:
        return u'#{}#'.format(phrase)
    else:
        return title
