# -*- coding: utf-8 -*-
from boto.s3.connection import S3Connection
from datetime import datetime, timedelta
from os import remove, rename
from os.path import basename
import requests
import tarfile
from yt import wrapper as yt
from const import CONFIG, SECRET
from robot.errs import CurrencyError


def get_dates(days, from_yt=False, **kwargs):
    if kwargs.get('first_date') is not None and kwargs.get('last_date') is not None:
        return {'first_date': str(kwargs['first_date']), 'last_date': str(kwargs['last_date'])}

    if from_yt:
        yt_client = yt.YtClient(token=SECRET['token'], proxy='hahn')
        table_values = list(yt_client.read_table(
            CONFIG['yt_agg_path'] + kwargs['report_name'] + '.info',
            format="<encode_utf8=%false>json")
        ).pop()
        first_date, last_date = table_values['DateBegin'], table_values['DateFinish']

    else:
        last_date = datetime.now() - timedelta(days=3)
        first_date = (last_date - timedelta(days=days)).strftime('%Y-%m-%d')
        last_date = last_date.strftime('%Y-%m-%d')

    return {'first_date': first_date, 'last_date': last_date}


def normalize_login(login):

    return login.strip().lower().replace('.', '-')


def get_login_clid(df):
    if df.empty:
        return 'Empty'

    clids = df.ClientID.unique().tolist()
    if clids:
        return clids.pop()
    else:
        return 'Empty'


def get_login_currency(df):
    if df.empty:
        return 'Empty'

    cur_list = df.Currency.unique().tolist()
    if cur_list:
        return cur_list.pop().replace('_', '')
    else:
        return 'Empty'


def get_reports_currency(cur_list):
    cur_list = [cur for cur in list(set(cur_list)) if cur != 'Empty']
    if len(cur_list) > 1:
        raise CurrencyError(u'different currencies between reports ({})'.format(u', '.join(cur_list)))

    if cur_list:
        return cur_list.pop()
    else:
        return 'Empty'


def rename_currency(report_path):
    report_name = basename(report_path)
    cur = report_name.split('_')[1:len(report_name.split('_')) - 2]

    new_report_path = report_path.replace('_'.join(cur), ''.join(cur))
    rename(report_path, new_report_path)

    return new_report_path


def create_s3_connection():
    conn = S3Connection(
        host=CONFIG['S3_API']['host'],
        aws_access_key_id=SECRET['S3_API']['access_key_id'],
        aws_secret_access_key=SECRET['S3_API']['secret_access_key'],
        is_secure=False
    )

    return conn


def create_new_key(bucket, file_path, **metadata):
    obj = bucket.new_key(basename(file_path))
    for k, v in metadata.iteritems():
        obj.set_metadata(k, v)
    obj.set_contents_from_filename(file_path, replace=True)
    return obj


def load_from_s3(path, **kwargs):
    if kwargs.get('obj'):
        url = CONFIG['NAMES']['url'].format(
            bucket=CONFIG['S3_API']['mini_bucket'], host=CONFIG['S3_API']['host'], key=kwargs['obj'].key)
    else:
        url = kwargs['url']

    request = requests.get(url)
    with open(path, 'wb') as fd:
        fd.write(request.content)


def get_last_modified(bucket, obj):
    return datetime.strptime(bucket.get_key(obj.key).last_modified, '%a, %d %b %Y %H:%M:%S %Z')


def make_tar_file(tar_path, files):
    with tarfile.open(tar_path, 'w:gz') as tar:
        for file_ in files:
            tar.add(file_, basename(file_))
            remove(file_)

    return tar_path
