#!/usr/bin/python3

import sys
import json
from lib.common import api_call
from config_file import xivo_ip, ws_user, ws_pass

method = "POST"
HEADERS = {
    "Content-Type": "application/json",
}


def get_auth_token():
    global HEADERS
    auth = (ws_user, ws_pass)
    url = f"https://{xivo_ip}:9497/0.1/token"
    data = {
        "backend": "xivo_service",
        "expiration": 600
    }
    payload = json.dumps(data)
    
    response = api_call(method, url, HEADERS, payload, auth)
    token = json.loads(response.text)['data']['token']
    print(token)
    HEADERS["X-Auth-Token"] = f"{token}"


def agents_action(action):
    url = f"https://{xivo_ip}:9493/1.0/agents/{action}"
    api_call(method, url, HEADERS)


def agent_action(action, agent_number, context):
    url = f"https://{xivo_ip}:9493/1.0/agents/by-number/{agent_number}/{action}"
    data = {
        "extension": f"{agent_number}",
        "context": f"{context}"
    }
    payload = json.dumps(data)
    api_call(method, url, HEADERS, payload)


def main():
    action = sys.argv[1]
    if action == "logoff" and sys.argv[2] == "all" or action == "relog":
        print(f"{action} all agents..")
        get_auth_token()
        agents_action(action)
        exit()
    elif action == "login" or action == "logoff":
        first_exten = int(sys.argv[2])
        count = int(sys.argv[3])
        context = sys.argv[4]
        print(f"{action} agents..")
        get_auth_token()
        for agent_number in range(first_exten, first_exten + count):
            agent_action(action, agent_number, context)
        exit()
    else:
        print("Please ! Enter a valid action (login, logoff, logoff_all and relog) as the variable action")


if __name__ == "__main__":
    main()