from .widget_sources.admin_query_ui import Ui_Form

from PySide6 import QtWidgets, QtCore
from src import Icon
from src.backend import Database


class AdminQueryWidget(QtWidgets.QWidget, Ui_Form):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(self)
        self.setWindowIcon(Icon("db_search").icon)
        self.db = Database()
        # Connect the button click to the method
        self.sendquery.clicked.connect(self.on_pushButton_clicked)

    def on_pushButton_clicked(self):
        # Handle button click event
        self.queryResult.setRowCount(0)  # Clear previous results
        request_text = self.sqlquery.toPlainText()
        if not request_text.strip():
            return

        data = self.db.query_db(request_text)
        print(data)
        table_names = (
            request_text.lower().split("select")[1].split("from")[0].split(",")
        )
        table_names = [name.strip() for name in table_names]
        # reset the horizontal header labels
        self.queryResult.setHorizontalHeaderLabels(table_names)
        for result in data:
            row_position = self.queryResult.rowCount()
            self.queryResult.insertRow(row_position)
            for column, value in enumerate(result):
                item = QtWidgets.QTableWidgetItem(str(value))
                item.setFlags(item.flags() & ~QtCore.Qt.ItemFlag.ItemIsEditable)
                self.queryResult.setItem(row_position, column, item)


def launch():
    app = QtWidgets.QApplication([])
    widget = AdminQueryWidget()
    widget.show()
    app.exec()
