import os
import sqlite3

from PyQt5.QtCore import QThread, QVariant
from qgis.PyQt import QtWidgets, uic, QtCore
from qgis.PyQt.QtCore import pyqtSignal

from .cyanlove_config_read_intfile import readconfig

FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'cyanlove_delete_table_sqlite_layer_base.ui'))

# 配置文件int格式
pathsaveint = os.path.join(os.path.dirname(__file__), 'config.ini')

class cyanlove_delete_table_sqlite_layer(QtWidgets.QDockWidget, FORM_CLASS):

    def __init__(self, parent=None):
        super(cyanlove_delete_table_sqlite_layer, self).__init__(parent)
        self.export_thread = None
        self.setupUi(self)
        self.setFloating(True)
        self.setWindowFlags(QtCore.Qt.Dialog)  # 使对话框始终在前
        self.setWindowModality(QtCore.Qt.ApplicationModal)
        self.btn_delete.clicked.connect(self.delete_sqlite_table)
        self.btn_update.clicked.connect(self.update_sqlite_table)
        # 初始化调用获取sqlite表
        self.initget_sqlite_table()

    def initget_sqlite_table(self):
        db_path = readconfig.read_ini_file('Settings', 'sqlite_栅格分析')
        # 连接到 SQLite 数据库
        conn = sqlite3.connect(db_path, timeout=5)
        cursor = conn.cursor()
        try:
            # 执行查询以获取表名
            cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
            # 获取所有表名
            table_names = [row[0] for row in cursor.fetchall()]
            # 过滤掉空字符串
            table_names = [name for name in table_names if name]  # 只保留非空的表名
            self.comboBox.clear()
            self.comboBox.addItems(table_names)
            self.comboBox.setCurrentIndex(0)

        except Exception as e:
            self.label_show.setText(f"错误：{str(e)}")
        finally:
            # 关闭游标和连接
            cursor.close()
            conn.close()
    # 刷新表
    def update_sqlite_table(self):
        self.label_show.setText(f"开始刷新...")
        self.initget_sqlite_table()
        self.label_show.setText(f"Sqlite表刷新重置完毕！")

    def delete_sqlite_table(self):
        # 获取当前选中的表名
        table_name = self.comboBox.currentText()
        if not table_name:
            self.label_show.setText("未选中任何表，请先选择表")
            return

        # 确认删除（可选，提升用户体验）
        reply = QtWidgets.QMessageBox.question(
            self,
            "确认删除",
            f"确定要删除表「{table_name}」吗？\n此操作不可恢复！",
            QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No,
            QtWidgets.QMessageBox.No
        )
        if reply != QtWidgets.QMessageBox.Yes:
            return

        # 读取数据库路径
        db_path = readconfig.read_ini_file('Settings', 'sqlite_栅格分析')
        conn = None
        cursor = None
        try:
            conn = sqlite3.connect(db_path, timeout=5)
            cursor = conn.cursor()
            # 执行删除表操作（表名来自系统表，安全）
            cursor.execute(f"DROP TABLE IF EXISTS `{table_name}`")
            conn.commit()
            self.label_show.setText(f"表「{table_name}」已成功删除！")
            # 刷新表下拉列表
            self.initget_sqlite_table()
        except Exception as e:
            self.label_show.setText(f"删除失败：{str(e)}")
            if conn:
                conn.rollback()
        finally:
            if cursor:
                cursor.close()
            if conn:
                conn.close()