import db_utils


def api_exploit_get_targets_stats(service, targets, thread_struct, db_name):
    db = db_utils.connect(db_name)
    data = db_utils.get_count_attacks_for_single_opponents(db)
    db.close()
    TOTAL, SERVICE, OPPONENT = 0, 1, 2
    response = {'targets': []}
    default_all = targets is None or len(targets) == 0
    for row in data:
        if row[SERVICE] == service and (default_all or row[OPPONENT] in targets):
            try:
                thread_status = thread_struct[row[SERVICE]][row[OPPONENT]].is_active()
            except KeyError:
                thread_status = 0
            target_info = {"name": row[OPPONENT], "flag": row[TOTAL], "active": thread_status}
            response['targets'].append(target_info)
    return response


def api_exploit_switch_state(service, targets, thread_struct):
    default_all = targets is None or len(targets) == 0
    result = {"result": "success", "switched": 0, "target_errors": 0}
    try:
        service_threads = thread_struct[service]
        for opponent in service_threads:
            if default_all or opponent in targets:
                try:
                    service_threads[opponent].switch_state()
                    result['switched'] += 1
                except KeyError:
                    result['target_errors'] += 1
        return result
    except KeyError:
        return {"error": "Invalid service"}


def api_exploit_kill(service, targets, thread_struct):
    default_all = targets is None or len(targets) == 0
    result = {"result": "success", "killed": 0, "target_errors": 0}
    try:
        service_threads = thread_struct[service]
        for opponent in service_threads:
            if default_all or opponent in targets:
                try:
                    service_threads[opponent].kill()
                    service_threads.pop(opponent)
                    result['killed'] += 1
                except KeyError:
                    result['target_errors'] += 1
        return result
    except KeyError:
        return {"error": "Invalid service"}
