from pathlib import Path
import base64
import signal
import time
import sys

from TaskOrcAPI import TaskOrchestratorAPI

class TestProcess1():
    stop = False
    def __init__(self):
        self.process_cmd_arguments(sys.argv[1].split("|"))
        self.robot_guid, self.host = self.get_settings()
        self.headers = {
            'Authorization': 'Basic ' + \
            base64.b64encode(self.robot_guid.encode('utf-8')).decode('utf-8')
        }

        self.TOA = TaskOrchestratorAPI(self.robot_guid, self.host, self.headers)
        signal.signal(signal.SIGBREAK, self.stop_process)

    # обработать аргументы командной строки
    def process_cmd_arguments(self, argv):
        self.process_version_guid = argv[0]
        self.job_guid = argv[1]
        self.settings_path = argv[2]
    
    def get_settings(self):
        with open(self.settings_path, "r", encoding="utf-8") as file:
            settings = file.read()
        settings = [elem.replace("\n", "") for elem in settings.split("\n")]

        return settings[0], settings[1]
    
    def stop_process(self, signal, frame):
        self.stop = True 

    def robot_work(self):
        n = 0
        while n < 15:
            time.sleep(1)
            self.TOA.add_new_log_entry(
                self.process_version_guid, self.job_guid,
                message = f"TestVersionProcess2 {n}"
            )
            if self.stop:
                self.TOA.add_new_log_entry(
                    self.process_version_guid, self.job_guid,
                    message = f"TestVersionProcess2 stop {n}"
                )
                sys.exit()

            n += 1

        self.TOA.add_new_log_entry(
            self.process_version_guid, self.job_guid,
            message = f"TestVersionProcess2 success {n}"
        )

test = TestProcess1()
test.robot_work()