# -*- coding: utf-8 -*-
import csv
import logging
from os import remove
from os.path import basename, exists, join
import tarfile
from const import CONFIG
from utils import (
    create_new_key,
    get_login_clid,
    get_login_currency,
    get_reports_currency,
    load_from_s3,
    make_tar_file,
    normalize_login,
    rename_currency
)

logger = logging.getLogger(__name__)


def make_report_mini_sources(task, worker, bucket):
    logger.debug('%s: make %s-report mini-sources', task.issue.key, worker.report_name)

    src = {}
    df = worker.res_tables['%s.data' % worker.report_name]
    for login in worker.logins:
        tmp_df = df[df['Login'].str.contains(login)].copy()  # предварительная фильтрация
        # приведение строки с логинами через запятую в список
        tmp_df['Login'] = tmp_df.Login.apply(lambda cell: cell.split(','))
        tmp_df = tmp_df[tmp_df.Login.apply(lambda cell: login in cell)]  # фильтрация по вхождению в список
        tmp_df['Login'] = login

        params = {
            'report_name': worker.report_name,
            'hashed_cids': task.params['hashed_cids'],
            'login': login,
            'clid': get_login_clid(tmp_df),
            'cur': get_login_currency(tmp_df),
            'date_1': task.reports[worker.report_name]['first_date'],
            'date_2': task.reports[worker.report_name]['last_date']
        }
        tsv_path = join(task.path, CONFIG['NAMES']['tsv'].format(**params))
        tmp_df.to_csv(tsv_path, sep='\t', index=False, encoding='utf-8', quoting=csv.QUOTE_NONE)
        tar_path = make_tar_file(join(task.path, CONFIG['NAMES']['mini_src'].format(**params)),
                                 worker.make_files() + [tsv_path])

        src[login] = create_new_key(bucket, tar_path, clid=params['clid'], currency=params['cur'], rev=worker.rev)

    return src


def make_login_sources(task, login, bucket):
    logger.debug('%s: make ta-sources for %s', task.issue.key, login)

    src = {}
    for report_name in task.reports.keys():
        obj = task.mini_src.get(report_name, {}).get(login)
        src[report_name] = {'files': unpack_login_report_mini(task, obj=obj),
                            'currency': obj.get_metadata('currency')}
    src['cs_reports'] = get_login_cs_sources(task, login)

    files = []
    [files.extend(report['files']) for report in src.itervalues()]

    cur = get_reports_currency([report['currency'] for report in src.itervalues()])
    tar_path = make_tar_file(
        join(task.path, CONFIG['NAMES']['ta_src'].format(
            issue_key=task.issue.key, login=login, cur=cur)),
        files)
    return create_new_key(bucket, tar_path)


def get_login_cs_sources(task, login):
    logger.debug('%s: collect ta-sources from robot-constructor-cs', task.issue.key)

    try:
        last_date = [com for com in task.issue.comments if u'Отчёт по подсветке строится.' in com.text].pop().createdAt
        cs_src_comments = [com.text for com in task.issue.comments if com.createdBy.login == 'robot-constructor-cs' and
                           u'Highlight result' in com.text and
                           com.createdAt > last_date]
        cs_src_comments = [com.replace('((', '').replace('))', '').split('\n')[1].split(' ') for com in cs_src_comments]
        url = [com[0] for com in cs_src_comments
               if login in [normalize_login(part) for part in com[1].split('_')]].pop()

    except IndexError:
        return {'files': [], 'currency': 'Empty'}

    except Exception as exc:
        logger.exception('%s: Oops!', task.issue.key)
        raise exc

    files = unpack_login_report_mini(task, url=url)
    cur = get_reports_currency([basename(file_).split('_')[1] for file_ in files])
    return {'files': files, 'currency': cur}


def unpack_login_report_mini(task, **kwargs):
    results = []

    tar_path = join(task.path, kwargs['obj'].key) if kwargs.get('obj') \
        else join(task.path, kwargs['url'].split('/')[-1])
    if not exists(tar_path):
        load_from_s3(tar_path, **kwargs)

    tar_file = tarfile.open(tar_path, 'r')
    tar_file.extractall(task.path)
    if kwargs.get('obj'):
        [results.append(join(task.path, file_.name)) for file_ in tar_file.members]
    else:
        [results.append(join(task.path, file_.name)) for file_ in tar_file.members
         if 'keywords.tsv' in file_.name or 'mobile.tsv' in file_.name]
        results = [rename_currency(file_) for file_ in results]

    if not task.debug:
        remove(tar_path)

    return results
