# -*- coding: utf-8 -*-
from datetime import datetime
import logging
from os import environ
from const import CONFIG, USER_VARS
from reports.utils import create_s3_connection, get_last_modified

logger = logging.getLogger(__name__)


def delete_old_revisions():
    logger.info('Remove old revisions')
    cur_revs = get_revisions()
    conn = create_s3_connection()
    bucket = conn.get_bucket(CONFIG['S3_API']['mini_bucket'])

    src_cnt, old_src_cnt = sum(1 for _ in bucket), 0
    for obj in bucket:
        obj = bucket.get_key(obj.key)
        if obj.metadata.get('rev'):
            if obj.metadata['rev'] not in cur_revs:
                old_src_cnt += 1
                obj.delete()
    logger.info('%i/%i sources with old revisions were removed', old_src_cnt, src_cnt)


def delete_old_tasks():
    logger.info('Remove old tasks')
    conn = create_s3_connection()
    bucket = conn.get_bucket(CONFIG['S3_API']['ta_bucket'])

    objs = [obj for obj in sorted(bucket, key=lambda obj_: get_last_modified(bucket, obj_))]
    old_src_cnt = 0
    for obj in objs:
        if (datetime.now() - get_last_modified(bucket, obj)).days > 40:
            old_src_cnt += 1
            obj.delete()
        else:
            break
    logger.info('%i/%i old tasks were removed', old_src_cnt, len(objs))


def get_revisions():
    rev_keys = []
    for report_name, report in CONFIG['REPORTS'].iteritems():
        if report.get('rev'):
            rev_keys.append(report['rev'])
        if report.get('rev_agg'):
            rev_keys.append(report['rev_agg'])

    revisions = []
    for rev_name in rev_keys:
        revisions.append(environ.get(rev_name, USER_VARS[rev_name]))

    return revisions
