# -*- coding: utf-8 -*-
from os import remove
from os.path import basename, dirname, join
import pandas as pd
from tempfile import _get_candidate_names
from zipfile import ZipFile
from camp_builder import CONFIG


def format_user_keys(dict_list, keys):
    for dict_ in dict_list:
        for key in keys:
            for case, prefix in CONFIG['case_prefix'].iteritems():
                dict_[key] = dict_[key].replace(u'гео{}'.format(prefix), u'geo_{}'.format(case))
                dict_[key] = dict_[key].replace(u'гео2{}'.format(prefix), u'geo2_{}'.format(case))
            dict_[key] = dict_[key].replace(u'гео', 'geo')

    return dict_list


def mixed_geo(gb_list, dir_list):
    geo_list = []

    for geo_dict_1 in gb_list:
        tmp_dict = geo_dict_1.copy()
        tmp_dict['Directions'] = []

        for geo_dict_2 in dir_list:
            if geo_dict_1['Geo'] != geo_dict_2['Geo']:
                tmp_dict['Directions'] += [geo_dict_2]

        geo_list.append(tmp_dict)

    return geo_list


def get_geo_kwargs(geobase=None, is_dest=False):
    if geobase:
        kwargs = {
            'geo': geobase['Runame'],
            'geo_genitive': geobase['RunameGenitive'],
            'geo_dative': geobase['RunameDative'],
            'geo_accusative': geobase['RunameAccusative'],
            'geo_ablative': geobase['RunameInstrumental'],
            'geo_prepositional': geobase['RunamePrepositional']
        }
    else:
        kwargs = {}
        for k in ['geo', 'geo_genitive', 'geo_dative', 'geo_accusative', 'geo_ablative', 'geo_prepositional']:
            kwargs[k] = None

    if is_dest:
        keys = kwargs.keys()
        for k in keys:
            new_key = k.replace('geo', 'geo2')
            kwargs[new_key] = kwargs.pop(k)

    return kwargs


def to_title(text):
    return u''.join([text[0].upper(), text[1:]])


def read_ws(f_path, ws_name, parse_cols, columns, **kwargs):
    df = pd.read_excel(f_path, sheetname=ws_name, parse_cols=parse_cols, ecoding='utf-8', **kwargs).dropna(how='all')
    df = df.rename(columns=columns)
    df = df.fillna('')

    column_types = {
        'GroupID': unicode,
        'GroupName': unicode
    }
    for column_name in df.columns:
        if column_types.get(column_name):
            df[column_name] = df[column_name].astype(column_types[column_name])

    return df.to_dict(orient='records')


def make_camp_file(f_name, ads):
    f_path = join(join(get_tmp_path(), f_name))

    df = pd.DataFrame(ads)
    df['Bid'] = df['Bid'].astype(pd.np.float)
    df = df.rename(columns=CONFIG['dc_cols'])

    df.loc[:, CONFIG['col_order']].to_csv(f_path, sep='\t', index=False, encoding='utf-16', decimal=',')
    return f_path


def make_zip_file(files, zip_name):
    zip_path = join(join(get_tmp_path(), zip_name))

    zip_file = ZipFile(zip_path, 'w')
    for file_ in files:
        zip_file.write(file_, arcname=basename(file_))
        remove(file_)

    zip_file.close()

    return zip_path


def get_tmp_path():
    return join(dirname(dirname(__file__)), 'tmp')


def gen_tmp_name():
    return next(_get_candidate_names())
