import logging
logging.basicConfig(level=logging.INFO)
import sys
reload(sys)
sys.setdefaultencoding('utf-8')

import config
from utils import *
import rutracker_api as api

data = api.get_forum_torrents_status(2092)
#print len(data.keys())
zero_seeds_torrent_ids = [thread for thread in data.keys()
    if len(data[thread]) == 2 and data[thread][1] == 0 and data[thread][0] in (2, 8)]
print len(zero_seeds_torrent_ids)

with open('/tmp/sha1', 'rt') as f:
    already_have_downloads = set(f.read().splitlines())

zero_seeds_torrent_hashes = api.get_tor_hash(zero_seeds_torrent_ids)
zero_seeds_torrent_ids = [torrent_id for torrent_id in zero_seeds_torrent_ids
    if zero_seeds_torrent_hashes[torrent_id].lower() not in already_have_downloads]
print len(zero_seeds_torrent_ids)

for i in range(0, len(zero_seeds_torrent_ids)):
    print 'processing {} out of {}'.format(i, len(zero_seeds_torrent_ids))
    id = zero_seeds_torrent_ids[i]
    with open('/tmp/dl/{}.torrent'.format(id), 'wb') as f:
        api.reliable_download_torrent(f, config.keeper_user_id, config.keeper_api_key, id)

    def trim_stat(stat):
        remove_keys = [ k for k, v in stat.iteritems() if v.cnt <= 24 * 5 ]
        for key in remove_keys:
            del stat[key]

    trim_stat(stat.local)
    trim_stat(stat.remote)

    #local_sorted = sorted(stat.local.items(), key=lambda tpl: -tpl[1].avg())
    #remote_sorted = sorted(stat.remote.items(), key=lambda tpl: tpl[1].avg())

    local_strong = [str(tpl[0]) for tpl in stat.local.items() if tpl[1].avg() > 2.5]
    remote_dying = [str(tpl[0]) for tpl in stat.remote.items() if tpl[1].avg() < 1]

    local_strong = [sha1.lower() for sha1 in api.get_tor_hash(local_strong).values() if sha1]
    remote_dying = api.get_tor_hash(remote_dying)

    local_strong = [sha1 for sha1 in local_strong if qbt.is_torrent_exists(sha1)]
    remote_dying = [kv[0] for kv in remote_dying.iteritems() if not qbt.is_torrent_exists(kv[1])]

    print "Weak local: {}".format(sum(int(tpl[1].avg() < 1) for tpl in stat.local.items()))
    print "Strong local: {}".format(len(local_strong))
    print "Dying remote: {}".format(len(remote_dying))
    continue

    qbt.remove_torrents(local_strong)

    for i in range(0, len(remote_dying)):
        print 'processing {} out of {}'.format(i, len(remote_dying))
        id = remote_dying[i]