# Thanks gawgua for all the reverse engineering work he has done.
# Almost all codes here are from him, I just made some changes to make it work with my project.
import hashlib
import platform
import random
from akademiya.constants import PLATFORM_DIRS


def _nt_get_window_id():
    import clr  # type: ignore
    import hashlib

    clr.AddReference("System.Management")
    from System.Management import ManagementScope, ManagementObjectSearcher, ObjectQuery  # type: ignore

    def getCSProductUUID():
        managementScope = ManagementScope("\\\\.\\ROOT\\cimv2")
        objectQuery = ObjectQuery("SELECT * FROM Win32_ComputerSystemProduct")
        managementObjectCollection = ManagementObjectSearcher(
            managementScope, objectQuery
        ).Get()
        text = ""
        for managemenBaseObject in managementObjectCollection:
            text += managemenBaseObject["UUID"]
            if text != "" and text.strip() != "":
                break
        return text

    def getDiskDriveSerial():
        managementScope = ManagementScope("\\\\.\\ROOT\\cimv2")
        objectQuery = ObjectQuery("SELECT * FROM Win32_DiskDrive")
        managementObjectCollection = ManagementObjectSearcher(
            managementScope, objectQuery
        ).Get()
        text = ""
        for managemenBaseObject in managementObjectCollection:
            text += managemenBaseObject["UUID"]
            if text != "" and text.strip() != "":
                break
        return text

    text = getCSProductUUID()
    if text == "":
        text = getDiskDriveSerial()
    text = text.replace("-", "") + "WINDOWID"
    return hashlib.md5(text.encode("utf-8")).hexdigest()[0:16]


def calculate_window_id():
    PLATFORM_DIRS.site_data_path.mkdir(parents=True, exist_ok=True)
    if PLATFORM_DIRS.site_data_path.joinpath("window_id").is_file():
        return PLATFORM_DIRS.site_data_path.joinpath("window_id").read_text().strip()
    else:
        result: str = ""
        if platform.system() == "Windows":
            result = _nt_get_window_id()
        else:
            result = random.randbytes(16).hex()[0:16]
        PLATFORM_DIRS.site_data_path.joinpath("window_id").write_text(result)
        return result


def calculate_serial():
    text = calculate_window_id() + "SERIAL"
    return hashlib.md5(text.encode("utf-8")).hexdigest()[0:16]


def get_unique_key():
    t = calculate_window_id()
    t2 = calculate_serial()
    t4 = f"{t}#{t2}#{t2}"
    t6 = "CA" + hashlib.md5(t4.encode("utf-8")).hexdigest()[-10:]
    t8 = hashlib.md5(t6.encode("utf-8")).hexdigest()[-4:]
    return t6 + t8
