from PyQt5.QtCore import QObject, QEvent, Qt
from PyQt5.QtWidgets import QToolBar, QMessageBox
from qgis.utils import iface
from cryptography.fernet import Fernet
import json
import os
import platform
import winreg
import datetime
import socket


def get_qgis_install_dir():
    # 尝试从环境变量获取
    qgis_env = os.getenv('QGIS_PREFIX_PATH')
    if qgis_env:
        return f'{qgis_env.replace("apps/qgis-ltr", "")}bin'
    # 尝试从Windows注册表获取
    if platform.system() == "Windows":
        sub_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, r'Software\QGIS')
        try:
            qgis_dir, _ = winreg.QueryValueEx(sub_key, 'QGIS_PREFIX_PATH')
            return qgis_dir
        except WindowsError:
            pass
    # 常见的安装路径
    default_paths = [
        os.path.join(os.path.expanduser('~'), 'AppData\Local\QGIS\QGIS3'),
        r'C:\Program Files\QGIS 3.X',
        r'C:\Program Files (x86)\QGIS 3.X',
    ]
    for path in default_paths:
        if os.path.exists(path):
            return path
    return None


def str_to_time(time_str):
    return datetime.datetime.strptime(time_str, "%Y-%m-%d %H:%M:%S")


def str_to_dict(string):
    # 去除首尾的花括号
    string = string.strip("{}")
    # 分割每个键值对
    pairs = string.split(", ")
    # 创建空字典
    result = {}
    # 遍历键值对并添加到字典中
    for pair in pairs:
        key, value = pair.split(": ")
        # 去除键和值两边的引号
        key = key.strip("'")
        value = value.strip("'")
        # 添加到字典中
        result[key] = value
    return result


def on_initialization_completed():
    print("QGIS 初始化完成！")
    iface.mainWindow().setWindowTitle("无标题工程 - 四维数码")
    main_window = iface.mainWindow()
    if main_window.findChild(QToolBar, 'ProcessingAlgorithms'):
        main_window.findChild(QToolBar, 'ProcessingAlgorithms').setVisible(0)
    # 获取所有动作
    # all_actions = iface.allActions()
    #
    # # 遍历所有动作并连接触发信号
    # for action in all_actions:
    #     action.triggered.connect(on_action_triggered)
    print("注册事件")

    # 创建事件过滤器实例
    event_filter = ClickEventFilter(main_window)

    # 安装事件过滤器到地图画布
    main_window.installEventFilter(event_filter)

    # 程序许可验证
    machine_name = socket.gethostname()
    current_time = datetime.datetime.now()
    qgis_dir = get_qgis_install_dir()
    licensepath = f"{qgis_dir}\\license.txt"
    # 打开文件并读取内容
    # text = []
    # with open(licensepath, 'r') as file:
    #     for line in file:
    #         text.append(line.replace('\n', ' '))
    # # 打印文件内容
    # print(text)
    #
    # try:
    #     # 尝试执行的代码
    #     fernet = Fernet(text[0].encode("utf-8"))
    #     decrypted_message = fernet.decrypt(text[1].encode("utf-8"))
    #     license = decrypted_message.decode('utf-8')
    #     licenseDict = str_to_dict(license)
    #     host = licenseDict["host"]
    #     date = licenseDict["license"]
    #
    #     time_str = f"{date} 23:59:59"
    #     licensetime = str_to_time(time_str)
    #     if host != machine_name:
    #         licenseError("机器名错误！")
    #         exit(1)
    #     elif current_time > licensetime:
    #         licenseError("许可已过期！")
    #         exit(1)
    #     else:
    #         print("许可正常")
    #         # print(f"解密的消息: {decrypted_message.decode('utf-8')}")
    # except Exception as e:
    #     # 处理异常的代码
    #     licenseError("许可文件解析问题！")
    #     exit(1)


def licenseError(message):
    QMessageBox.critical(None, 'Error', message)


class ClickEventFilter(QObject):
    def __init__(self, parent=None):
        super().__init__(parent)

    def eventFilter(self, obj, event):
        print("event")
        if event.type() == QEvent.MouseButtonPress:
            if event.button() == Qt.LeftButton:
                print("左键点击事件")
            elif event.button() == Qt.RightButton:
                print("右键点击事件")
            elif event.button() == Qt.MiddleButton:
                print("中键点击事件")
            return True  # 如果你返回True，则事件被过滤掉，不再传递给其他组件
        return super().eventFilter(obj, event)


# 连接信号到槽函数
iface.initializationCompleted.connect(on_initialization_completed)
