#!/usr/bin/python3

import json
from time import sleep
from libs.common import api_call, HEADERS
from libs.config import CONFIG
from libs.removing.agents_remover import try_get_queue_id, delete_agent_from_queue, delete_agent
from libs.removing.lines_remover import try_dissociate_device_from_line, delete_device, delete_line, try_dissociate_extension_from_line, delete_line, delete_extension
from libs.removing.users_remover import try_dissociate_user_from_line, delete_user

def delete_agents():
    agents_list = _get_resources_list("agents")

    for agent_id in agents_list:
        queue_id = try_get_queue_id(agent_id)
        if queue_id:
            delete_agent_from_queue(agent_id, queue_id)
            delete_agent(agent_id)
            sleep(1)


def delete_lines():
    lines_list = _get_resources_list("lines")

    for line_id in lines_list:
        line_config = _get_line_config(line_id)
        try_dissociate_device_from_line(line_config)
        delete_device(line_config)
        exten_id = try_dissociate_extension_from_line(line_config)
        delete_extension(exten_id)
        user_id = try_dissociate_user_from_line(line_id)
        delete_user(user_id)
        delete_line(line_id)
        sleep(1)
        

def _get_resources_list(resource_type):
    print(f"Fetching fetching all {resource_type} resources")
    url = f"{CONFIG['url_prefix']}/{resource_type}"
    response = json.loads(api_call("GET", url, HEADERS).text)
    resources_list = [resource['id'] for resource in response['items']]
    return resources_list


def _get_line_config(line_id):
    print(f"Fetching config for line {line_id}")
    url = f"{CONFIG['url_prefix']}/lines/{line_id}"
    line = json.loads(api_call("GET", url, HEADERS).text)
    return line


def remove_config():
    delete_agents()
    delete_lines()
