import time

try:
    from statuses import InternalStatus
except ModuleNotFoundError:
    from .statuses import InternalStatus


def process_task(task):
    task.validate_config()
    if task.status == InternalStatus.VALIDATED:
        task.define_hosts()
    if task.status != InternalStatus.FAILED_TO_START:
        task.start_test()
    while task.status not in (InternalStatus.FAILED_TO_START, InternalStatus.FAILED, InternalStatus.FINISHED):
        task.check_test_status()
        time.sleep(15)


def get_tanks_from_config(config):
    """
    Parses config and takes tank and port settings from neuploader meta.
    If they are empty, take tank and port from uploader meta.
    Return empty strings if both meta fields do not contain tank and port.

    :param config: Validated tank config
    :type config: dict
    :return: Tank and port values
    :rtype: set(str, str)
    """

    def get_meta_option_from_config(section, option):
        return config.setdefault(section, {}).setdefault('meta', {}).setdefault(option, '')

    tank = get_meta_option_from_config('neuploader', 'use_tank')
    port = get_meta_option_from_config('neuploader', 'use_tank_port')
    if not tank:
        tank = get_meta_option_from_config('uploader', 'use_tank')
        port = get_meta_option_from_config('uploader', 'use_tank_port')
    return tank, port


def get_target_from_config(config):
    """
    Parses config and takes tank and port settings from generator section.
    Ipv6 should be in brackets, or it's impossible to differ last part from port.
    By default takes phantom target, otherwise checks pandora section.
    """
    raw_target = config.setdefault('phantom', {}).setdefault('address', '')
    if not raw_target:
        raw_target = config.setdefault('pandora', {}).setdefault('config_content', {}).get('pools', [])[0].setdefault('gun', {}).get('target')
    try:
        if raw_target.startswith('nanny:'):
            host, port = raw_target, '80'
        else:
            host, port = raw_target.rsplit(':', 1)
    except ValueError:
        host, port = raw_target, '80'
    if raw_target.startswith('[') and raw_target.endswith(']'):
        host, port = raw_target, '80'
    return host, port


def rewrite_target_in_config(config, target_host, target_port):
    """
    Rewrites phantom.address set to nanny group with target host and target port
    """
    if config.setdefault('phantom', {}).get('enabled'):
        config['phantom']['address'] = '{host}:{port}'.format(host=target_host, port=target_port)
    elif config.setdefault('pandora', {}).get('enabled'):
        for pool in config['pandora']['config_content']['pools']:
            pool['gun']['target'] = '{host}:{port}'.format(host=target_host, port=target_port)
    return config
