from pathlib import Path
import datetime
import base64
import os

from RobotsOrcFramework import RobotsOrchestratorFramework

# pyinstaller -F -w --name=SherpaPython RobotsOrcRunner.py RobotsOrcFramework.py RobotsOrcAPI.py TaskOrcAPI.py

class RobotsOrchestratorRunner():
    def __init__(self):
        self.should_logoff = True
        self.config_path = f"{str(Path.home())}\AppData\Roaming\Sherpa RPA Python"
        self.path_scripts = f"{Path().resolve()}"
        self.settings_path = f"{self.config_path}\settings.txt"

    # Получить настройки
    def get_settings(self):
        if not os.path.exists(self.config_path):
            os.makedirs(self.config_path)
        if not os.path.exists(self.settings_path):
            message = "<< Введите guid робота >>\n<< Введите host робота >>\n<< Введите статус logoff робота >>"
            with open(self.settings_path, "w", encoding="utf-8") as file:
                file.write(message)
            return False
                
        with open(self.settings_path, "r", encoding="utf-8") as file:
            settings = file.read()
        settings = [elem.replace("\n", "") for elem in settings.split("\n")]

        robot_guid, host = settings[0], settings[1]
        headers = {
            'Authorization': 'Basic ' + \
            base64.b64encode(robot_guid.encode('utf-8')).decode('utf-8')
        }

        if len(settings) > 2:
            try: self.should_logoff = bool(int(settings[2]))
            except: pass

        return [robot_guid, host, headers]
    
    # Запуск фреймворка
    def run(self):
        result = self.get_settings()
        if type(result) == bool: return
        else: robot_guid, host, headers = result
        
        ROF = RobotsOrchestratorFramework(
            robot_guid, host, headers,
            self.settings_path, self.config_path, self.path_scripts, self.should_logoff
        )

        now = datetime.datetime.now()
        try:
            ROF.logs(f"\n-------------------Запуск от {str(now.strftime('%d-%m-%Y %H:%M'))}-------------------")
            ROF.logs(f"Путь для логов и файла настроек: ({self.config_path})\n")
            ROF.start_thread()
        except Exception as error: raise ValueError(error) 

ROR = RobotsOrchestratorRunner()
ROR.run()