import sqlite3
from threading import Lock
import time
from codes.common import clibs


def db_init(db_file):
    conn = sqlite3.connect(db_file, isolation_level=None, check_same_thread=False, cached_statements=2048, timeout=10.0)
    cursor = conn.cursor()
    cursor.execute("PRAGMA journal_mode=wal")
    cursor.execute("PRAGMA wal_checkpoint=TRUNCATE")
    cursor.execute("PRAGMA synchronous=normal")
    cursor.execute("PRAGMA temp_store=memory")
    cursor.execute("PRAGMA mmap_size=30000000000")
    cursor.execute("PRAGMA cache_size=200000")
    cursor.execute(
        """
        create table if not exists logs(
            id integer primary key autoincrement,
            timestamp DATETIME DEFAULT(STRFTIME('%Y-%m-%d %H:%M:%f', 'NOW', 'localtime')),
            level text,
            module text,
            content text
        )
        """
    )
    cursor.close()
    conn.close()

def db_lock(func):
    def wrapper(*args, **kwargs):
        try:
            Lock().acquire(True)
            ret = func(*args, **kwargs)
        finally:
            Lock().release()
        return ret
    return wrapper

def db_backup():
    t = time.strftime("%Y%m%d%H%M%S", time.localtime())
    db_file = clibs.base_path / "assets/database/toolbox.db"
    db_file_backup = clibs.base_path / f"assets/database/toolbox.{t}.db"
    if not (db_file.exists() and db_file.is_file()):
        db_init(db_file)
    else:
        db_file_backup.write_bytes(db_file.read_bytes())
        db_dir = clibs.base_path / "assets/database"
        db_list = [db for db in db_dir.glob("*.db")]
        print(f"db_list: {sorted(db_list)}")
        for db in sorted(db_list)[:-clibs.max_db_number]:
            db.unlink()

def db_conn():
    db_file = clibs.base_path / "assets/database/toolbox.db"
    conn = sqlite3.connect(db_file, isolation_level=None, check_same_thread=False, cached_statements=2048, timeout=10.0)
    cursor = conn.cursor()
    cursor.execute("PRAGMA journal_mode=wal")
    cursor.execute("PRAGMA wal_checkpoint=TRUNCATE")
    cursor.execute("PRAGMA synchronous=normal")
    cursor.execute("PRAGMA temp_store=memory")
    cursor.execute("PRAGMA mmap_size=30000000000")
    cursor.execute("PRAGMA cache_size=200000")
    return conn, cursor