import os
import pathlib
import datetime
import configparser
from abc import ABC, abstractmethod
from loguru import logger


class Config:
    """
    配置类，读取配置文件
    """

    def __init__(self, process_name):
        config_file = pathlib.Path(os.path.expanduser('~'), '.rpa/config/config.ini')
        config_parser = configparser.ConfigParser()
        config_parser.read(config_file, encoding='utf-8')
        process_config = {k: v for k, v in config_parser['global'].items()}
        if process_name in config_parser:
            process_config.update(config_parser[process_name])
        self.__dict__.update(process_config)


class BaseProcess(ABC):

    def __init_subclass__(cls, **kwargs):  # 子类必须定义process_name属性
        super().__init_subclass__(**kwargs)
        if not hasattr(cls, 'process_name') or not isinstance(cls.process_name, str):
            raise TypeError(f"类 {cls.__name__} 必须定义一个'process_name'的类属性，类型为str")

    def __init__(self):
        self.start_time = datetime.datetime.now()
        self.config = Config(self.process_name)

    @property
    def use_time(self):
        used = datetime.datetime.now() - self.start_time
        return f'运行用时：{used}'

    @abstractmethod
    def main_process(self, *args, **kwargs):
        pass

    def run(self, *args, **kwargs):
        logger.info(f'开始运行流程：{self.process_name}')
        try:
            self.main_process(*args, **kwargs)
        except Exception as e:
            logger.error(f"流程运行失败：{e}")
        finally:
            logger.info(f"流程运行结束：{self.use_time}")
