import os
import time
from abc import abstractmethod, ABC

from pyboot.config import ConfigManager
from pyboot.utils.log import Log

class Runner(ABC):

    @abstractmethod
    def __init__(self, config_path):
        ConfigManager.load_config_with(config_path)
        ConfigManager.print_config()
        self.config = ConfigManager.get("runner")
        self.workspace_config = self.config["workspace"]
        self.workspace_path = os.path.join(self.workspace_config["root_dir"], self.workspace_config["name"])
        lt = time.localtime()
        self.file_name = f"{lt.tm_year}_{lt.tm_mon}_{lt.tm_mday}_{lt.tm_hour}h{lt.tm_min}m{lt.tm_sec}s"
        self.load_workspace()

    @abstractmethod
    def run(self):
        pass

    def load_workspace(self, backup_name=None):
        if not os.path.exists(self.workspace_path):
            Log.info(f"workspace {self.workspace_config['name']} does not exists.")
            self.create_workspace(backup_name)
        else:
            Log.info(f"workspace {self.workspace_config['name']}")
            backup_config_dir = os.path.join(str(self.workspace_path), "configs")
            if not os.path.exists(backup_config_dir):
                os.makedirs(backup_config_dir)
            ConfigManager.backup_config_to(backup_config_dir, self.file_name, backup_name)

    def create_workspace(self, backup_name=None):
        Log.info("creating workspace: " + self.workspace_config["name"])
        os.makedirs(self.workspace_path)
        backup_config_dir = os.path.join(str(self.workspace_path), "configs")
        os.makedirs(backup_config_dir)
        ConfigManager.backup_config_to(backup_config_dir, self.file_name, backup_name)
        log_dir = os.path.join(str(self.workspace_path), "logs")
        os.makedirs(log_dir)
        cache_dir = os.path.join(str(self.workspace_path), "cache")
        os.makedirs(cache_dir)

    def print_info(self):
        table_size = 80
        Log.blue("+" + "-" * table_size + "+")
        Log.blue(f"| Workspace <{self.workspace_config['name']}>")
        Log.blue("+" + "-" * table_size + "+")
