import re
import time

from concurrent.futures import ThreadPoolExecutor

from load.projects.tank_finder.lib.tools import set_to_cache
from load.projects.tank_finder.lib.tools import get_tank_status, get_conductor_tanks, get_rtc_tanks
from load.projects.tank_finder.lib.config import logger

period = 15


def collect_status(tank):
    disk_usage = []
    status = get_tank_status(tank['tank'], tank['port'])

    if status is not None:
        for fs in status['fs_use']:
            percent_used = re.split('%', status['fs_use'][fs]['use_p'])
            if int(percent_used[0]) >= 70:
                disk_usage.append({
                    'name': status['fs_use'][fs]['mount'],
                    'percent_used': percent_used[0],
                    'mb_available': status['fs_use'][fs]['avail']
                })

        if status['is_testing']:
            response = {'status': 'busy'}
        elif not status['is_testing']:
            response = {'status': 'free'}
        user_activity = status['users_activity']

    else:
        disk_usage = ''
        user_activity = ''
        response = {'status': 'not available'}
        logger.info('Tank not available: {}'.format(tank['tank']))

    response.update({
        'hostname': tank['tank'],
        'port': tank['port'],
        'service': tank['service'],
        'data_centre': tank['dc'],
        'logged_users': user_activity,
        'top_used_resources': {'disk_usage': disk_usage}
    })

    # logger.info('{} tank status: {}'.format(tank['tank'], response))
    set_to_cache('status_{}'.format(tank['tank']), response)

    return response


def get_tanks_status(app):
    while True:
        tanks_common = get_rtc_tanks(app) + get_conductor_tanks(app)

        set_to_cache('tanks_common', tanks_common)

        start = time.time()

        with ThreadPoolExecutor(max_workers=20) as executor:
            [executor.submit(collect_status, tank) for tank in tanks_common]

        time_left = period-(time.time()-start)
        if time_left > 0:
            time.sleep(time_left)
