import requests
import urllib3
import json

class TaskOrchestratorAPI():
    def __init__(self, robot_guid, host, headers):
        requests.packages.urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
        self.host, self.robot_guid, self.headers = host, robot_guid, headers

    # Добавление новой задачи в очередь
    def add_task(
            self, queue_guid, parameters_task={"":""}, name='NewTask'
        ):

        new_task = {
            'queue_guid': queue_guid, 'name': name,
            'parameters': json.dumps(parameters_task)
        }
        req_result = requests.post(
            self.host + '/api/task/create', data=new_task,
            headers = self.headers, verify  =False
        )
        return json.loads(req_result.text)
    
    # Получаем последнюю задачу в очереди
    def get_task(self, queue_guid, status='0'):
        return requests.get(
            self.host + f'/api/task/filter/read/{queue_guid}/{str(status)}',
            headers = self.headers, verify=False
        )

    # Обновляем статус полученной задачи
    def update_task_status(self, task_guid, status=0):
        return requests.put(
            self.host + '/api/task/update',
            data = {'guid': task_guid, 'status': int(status)},
            headers = self.headers, verify=False
        )

    # Получаем ресурс (asset)
    def get_asset(self, asset_guid):
        script = f'/api/asset/read/{asset_guid}'
        req_result = requests.get(
            self.host + script, headers=self.headers, verify=False
        )
        return json.loads(req_result.text)

    # Обновляем ресурс
    def asset_update(self, asset_guid, text, name='NewName', password=False):
        asset_update = {
            'guid': asset_guid, 'name': name, 'text': text,
        }

        if type(password) != bool: asset_update['password'] = password

        req_result = requests.put(
            self.host + '/api/asset/update', data = asset_update,
            headers = self.headers, verify=False
        )
        return req_result

    # Добавляем новую запись в лог
    def add_new_log_entry(
            self, process_version_guid,
            job_guid, level='Info', message=''
        ):
        new_log = {
            'robot_guid': self.robot_guid,
            'process_version_guid': process_version_guid,
            'job_guid': job_guid, 'level': level, 'message': message
        }
        
        return requests.post(
            self.host + '/api/log/create', data=new_log,
            headers=self.headers, verify=False
        )




    



