#!/usr/bin/python3

import json
from libs.common import api_call, HEADERS
from libs.config import CONFIG


def try_dissociate_device_from_line(line_config):
    device_id = line_config["device_id"]
    line_id = line_config["id"]
    if device_id:
        _dissociate_device_from_line(device_id, line_id)


def delete_device(line_config):
    device_id = line_config["device_id"]
    print(f"Deleting device {device_id}")
    url = f"{CONFIG['url_prefix']}/devices/{device_id}"
    api_call("DELETE", url, HEADERS)


def try_dissociate_extension_from_line(line_config):
    exten = line_config["caller_id_num"]
    line_id = line_config["id"]
    exten_ids = _get_extensions_of_line(exten)
    if exten_ids:
        exten_id = exten_ids[0]
        _dissociate_extension_from_line(exten_id, line_id)
        return exten_id


def delete_extension(exten_id):
    print(f"Deleting extension {exten_id}")
    url = f"{CONFIG['url_prefix']}/extensions/{exten_id}"
    api_call("DELETE", url, HEADERS)


def delete_line(line_id):
    print(f"Deleting line {line_id}")
    url = f"{CONFIG['url_prefix']}/lines/{line_id}"
    api_call("DELETE", url, HEADERS)


def _dissociate_device_from_line(device_id, line_id):
    print(f"Removing device {device_id} from line {line_id}")
    url = f"{CONFIG['url_prefix']}/lines/{line_id}/devices/{device_id}"
    api_call("DELETE", url, HEADERS)


def _get_extensions_of_line(extension):
    print(f"Fetching id for line extension {extension}")
    url = f"{CONFIG['url_prefix']}/extensions"
    response = json.loads(api_call("GET", url, HEADERS).text)
    exten_ids = [item['id'] for item in response['items'] if item['exten'] == str(extension)]
    return exten_ids


def _dissociate_extension_from_line(exten_id, line_id):
    print(f"Removing exten {exten_id} from line {line_id}")
    url = f"{CONFIG['url_prefix']}/lines/{line_id}/extensions/{exten_id}"
    api_call("DELETE", url, HEADERS)

