# -*- coding:utf-8 -*-
"""
@Author  : xuxingchen
@Contact : xuxingchen@sinochem.com
@Desc    : 数据库处理基础方法
"""
import sqlite3

from config import DB_PATH
from utils.logger import Logger, new_dc


class SQLiteDatabaseEngine:
    def __init__(self, db_path: str = "demo.db") -> None:
        self.sqlite3 = sqlite3
        self.db_path = db_path
        self.connection = None
        self.cursor = None
        self.connect()

    def connect(self):
        """连接SQLite 数据库（如果数据库不存在则会自动创建）"""
        self.connection = self.sqlite3.connect(self.db_path)
        self.cursor = self.connection.cursor()
        Logger.init(new_dc(f"🔗 SQLite - {self.db_path} has connect successfully! 🔗", "[1;32m"))

    def disconnect(self):
        try:
            self.cursor.close()
            self.connection.close()
        except Exception as e:
            if type(e).__name__ != "ProgrammingError":
                Logger.error(f"{type(e).__name__}, {e}")
        Logger.info(new_dc(f"🔌 Disconnect from SQLite - {self.db_path}! 🔌", "[1m"))

    def exist(self, table_name):
        self.cursor.execute(
            f"SELECT name FROM sqlite_master WHERE type='table' AND name=?",
            (table_name,),
        )
        result = self.cursor.fetchone()
        if result:
            return True
        else:
            return False


class BaseTable:
    def __init__(self, connection=None, cursor=None):
        self.connection = connection
        self.cursor = cursor

    def set(self, connection, cursor):
        self.connection = connection
        self.cursor = cursor

    def execute(self, sql: str | list, params: tuple | list = ()):
        if isinstance(sql, list):
            for i, s in enumerate(sql):
                self.cursor.execute(s, params[i])
        else:
            self.cursor.execute(sql, params)
        self.connection.commit()

    def executemany(self, sql: str, params: list[tuple]):
        self.cursor.executemany(sql, params)
        self.connection.commit()

    def query(self, sql: str, params: tuple = ()):
        self.cursor.execute(sql, params)


class TableHandlerSingleton:
    _instance = None

    @classmethod
    def get_instance(cls):
        if cls._instance is None:
            db = SQLiteDatabaseEngine(db_path=DB_PATH)
            cls._instance = BaseTable(db.connection, db.cursor)
        return cls._instance


def get_table_handler():
    return TableHandlerSingleton.get_instance()
