# -*- coding: utf-8 -*-
import datetime
import sqlite3

from ddans.native.system import NSystem
from ddans.native.config import NConfig
from ddans.native.hook import NHook
from ddans.native.log import NLog


class DSqlite(object):

    def __init__(self, name: str):
        if not NHook.isvalid_str(name):
            return

        appData = NConfig.app_data("base")
        dbase = NSystem.join(appData, f"{name}.db")

        NSystem.ensure_dir(dbase)
        self.dbase = dbase

    def create_table(self, sql: str):
        try:

            if not NHook.isvalid_str(sql):
                return False

            # 连接到数据库
            with sqlite3.connect(self.dbase) as conn:
                # 创建一个 cursor 对象
                cur = conn.cursor()

                # # 创建表（如果不存在）
                # cur.execute('''CREATE TABLE IF NOT EXISTS users (
                #     id INTEGER PRIMARY KEY AUTOINCREMENT,
                #     name TEXT NOT NULL,
                #     age INTEGER NOT NULL
                #     email TEXT,
                #     created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                #     updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
                # )''')

                # 创建表
                cur.execute(sql)

                # 检查是否已存在 email 列，如果不存在则添加
                cur.execute("PRAGMA table_info(users)")
                columns = [column[1] for column in cur.fetchall()]
                if 'email' not in columns:
                    cur.execute("ALTER TABLE users ADD COLUMN email TEXT")

            return True
        except sqlite3.Error as e:
            NLog.error(f"create_table: {e}")
            return False
        except Exception:
            return False

    def alter_table(self, name: str, field: str, sql: str = None):
        try:

            if not NHook.isvalid_str(field) or not NHook.isvalid_str(name):
                return

            # 连接到数据库
            with sqlite3.connect(self.dbase) as conn:
                # 创建一个 cursor 对象
                cur = conn.cursor()

                # 检查是否已存在 email 列，如果不存在则添加
                cur.execute(f"PRAGMA table_info({name})")
                columns = [column[1] for column in cur.fetchall()]

                if NHook.isvalid_str(sql):
                    sql = f"ALTER TABLE users ADD COLUMN {field} TEXT"

                if 'field' not in columns:
                    cur.execute(sql)
                    # cur.execute("ALTER TABLE users ADD COLUMN email TEXT")
            return
        except sqlite3.Error as e:
            NLog.error(f"create_table: {e}")
            pass
        except Exception:
            pass

    def execute(self, name: str, sql: str, parameters=()):
        try:

            if not NHook.isvalid_str(sql) or not NHook.isvalid_str(name):
                return

            # 连接到数据库
            with sqlite3.connect(self.dbase) as conn:
                cur = conn.cursor()
                cur.execute(sql, parameters)
                conn.commit()
            return
        except sqlite3.Error as e:
            NLog.error(f"execute: {e}")
            pass
        except Exception:
            pass

    def update(self, name: str, fields: dict, conditions: dict):

        if not NHook.isvalid_str(name) or not NHook.isvalid(
                fields) or not NHook.isvalid(conditions):
            return

        # 构建更新语句
        updates = []
        update_parameters = []
        for key, value in fields.items():
            updates.append(f"{key} = ?")
            update_parameters.append(value)

        # 添加更新时间
        updates.append('updated_at = ?')
        update_parameters.append(datetime.now())

        # 构建条件语句
        where_conditions = []
        condition_parameters = []
        for key, value in conditions.items():
            where_conditions.append(f"{key} = ?")
            condition_parameters.append(value)

        # 构建完整的更新语句
        sql = (f"UPDATE {name} SET {', '.join(updates)} "
               f"WHERE {' AND '.join(where_conditions)}")
        parameters = update_parameters + condition_parameters
        self.execute(name, sql, parameters)
