import json
import sys
import base64
import time
from typing import Callable, Any
from PySide6.QtWidgets import QApplication, QWidget, QMessageBox, QMainWindow
from PySide6.QtGui import QIcon, QPixmap, QShortcut
from PySide6.QtCore import Qt
from codes.ui.login import Ui_login
from codes.ui.app import Ui_MainWindow
from codes.common.worker import Worker
from codes.common import clibs
from codes.common.secure_encrypt import PassCipher
from codes.common import db_operation

class LoginWindow(QWidget, Ui_login):
    def __init__(self):
        super().__init__()
        self.setupUi(self)
        self.pre_dos()

    def pre_dos(self):
        self.setWindowIcon(QIcon(f"{clibs.base_path}/assets/media/icon.ico"))
        self.lb_logo.setPixmap(QPixmap(f"{clibs.base_path}/assets/media/avatar.png"))
        self.lb_logo.setScaledContents(True)

        # bindings
        QShortcut("Esc", self).activated.connect(self.close)
        self.pb_login.clicked.connect(self.login)
        self.pb_cancel.clicked.connect(self.close)
        self.le_password.returnPressed.connect(self.login)

    def login(self):
        def login_failed():
            QMessageBox.warning(self, "告警", "\n用户名或密码不正确，请重新输入！")
            self.le_username.setText("")
            self.le_password.setText("")

        def gen_salt():
            clibs.salt = ""
            key = ""
            passwd = {idx: char for idx, char in enumerate(self.le_password.text() * 4)}
            for idx in range(32):
                char_i = 0 if ord(passwd[idx]) - clibs.code_dict[idx] < 0 else ord(passwd[idx]) - clibs.code_dict[idx]
                key += chr(char_i)
            clibs.salt = base64.urlsafe_b64encode(key.encode()).decode()

        def validate_login():
            # with open(f"{clibs.base_path}/assets/conf/config.json", mode="rt", encoding="utf-8") as f_conf:
            #     accounts = json.load(f_conf)["account"]
            # username = self.le_username.text()
            # if username not in accounts or len(self.le_password.text()) < 8:
            #     login_failed()
            #     return False
            #
            # gen_salt()
            # cipher = PassCipher(clibs.salt)
            # try:
            #     password = cipher.decrypt(accounts[username])
            # except ValueError:
            #     login_failed()
            #     return False
            #
            # if password != self.le_password.text():
            #     login_failed()
            #     return False

            self.mainWindow = MainWindow()
            self.mainWindow.show()
            self.close()
            self.deleteLater()
            return True
        
        validate_login()

    
class MainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self):
        super().__init__()
        self.conn = None
        self.cursor = None
        self.thread = None
        self.setupUi(self)
        self.pre_dos()

    def pre_dos(self):
        self.setWindowIcon(QIcon(f"{clibs.base_path}/assets/media/icon.ico"))
        db_operation.db_backup()
        self.conn, self.cursor = db_operation.db_conn()


    def launch(self, func, on_anything: Callable[..., Any] = print, *args, **kwargs):
        self.thread = Worker(func, *args, **kwargs)
        self.thread.started.connect(lambda: on_anything({"started": True}))
        self.thread.result.connect(on_anything)
        self.thread.error.connect(on_anything)
        self.thread.finished.connect(lambda: on_anything({"finished": True}))
        self.thread.start()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    login = LoginWindow()
    login.show()
    sys.exit(app.exec())
