import inspect
import shutil
import os
import time
from typing import Optional
import bcrypt

from PyQt5.QtCore import Qt, QUrl, QSize
from PyQt5.QtGui import QIcon
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QTreeWidget, QTreeWidgetItem, QMenu, QFileDialog, \
    QMessageBox, QInputDialog, QLineEdit, QPushButton, QHBoxLayout, QFormLayout, QToolBar
from PyQt5.QtWebEngineWidgets import *
import ftplib
import sys
from PostgreSQL import PostgreSQL
from Redis import Redis
import socket
from qgis.utils import iface


class Login(QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi()

    def setupUi(self):
        self.setWindowTitle("用户登录")
        self.resize(250, 100)
        self.username_edit = QLineEdit()
        self.password_edit = QLineEdit()
        self.password_edit.setEchoMode(QLineEdit.Password)
        current_directory = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
        self.setWindowIcon(QIcon(os.path.join(current_directory, "login.png")))
        login_button = QPushButton("登录")
        login_button.clicked.connect(self.login)
        layout = QFormLayout()
        layout.addRow("用户名", self.username_edit)
        layout.addRow("密码", self.password_edit)
        layout.addRow(login_button)
        self.setLayout(layout)

    def checklogin(self):
        redis = Redis()
        s = redis.getUsername()
        redis.close()
        if s is not None:
            app.quit()

    def login(self):
        username = self.username_edit.text()
        password = self.password_edit.text()
        if username is not None and password is not None:
            pgconn = PostgreSQL(schema='base')
            rows = pgconn.getPasswordByUsername(username)
            pgconn.close()
            if len(rows) == 0:
                QMessageBox.critical(self, "提示信息", "用户名错误！")
            else:
                userpass = rows[0][0]
                checked = bcrypt.checkpw(password.encode('utf-8'), userpass.encode('utf-8'))
                print(checked)
                if checked:
                    QMessageBox.information(self, "提示信息", "登录成功")
                    # 存储用户名到Redis
                    redis = Redis()
                    redis.setUsername(username)
                    s = redis.getUsername()
                    print(s)
                    redis.close()
                    app.quit()
                else:
                    QMessageBox.critical(self, "提示信息", "密码错误！")
        else:
            QMessageBox.critical(self, "提示信息", "请输入用户名、密码！")


if __name__ == '__main__':
    app = QApplication(sys.argv)
    login = Login()
    login.show()
    # login.checklogin()
    sys.exit(app.exec_())
    # time.sleep(0.5)
    # redis = Redis()
    # s = redis.getUsername()
    # redis.close()
    # if s is not None:
    #     app.quit()

