#!/usr/bin/env python3
# -*- coding: utf-8 -*-

from pathlib import Path
from string import Template
from typing import Dict, List, Optional

FILE_TEMPLETES: Dict[str, Template] = {
    "install.inf": Template(
        """
; ===========================================================
; Auto-Generated File
; ===========================================================
; This file has been automatically generated by a tool
; called 'clickgen'. For more information,
; visit: https://www.github.com/ful1e5/clickgen
; ===========================================================


; $theme_name
; $comment $website

[Version]
signature="$CHICAGO$"
$comment

[DefaultInstall]
CopyFiles = Scheme.Cur
AddReg    = Scheme.Reg,Wreg

[DestinationDirs]
Scheme.Cur = 10,"%CUR_DIR%"

[Scheme.Reg]
HKCU,"Control Panel\\Cursors\\Schemes","%SCHEME_NAME%",,$scheme_reg

[Wreg]
HKCU,"Control Panel\\Cursors",,0x00020000,"%SCHEME_NAME%"
$wreg
HKLM,"SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Runonce\\Setup\\","",,"rundll32.exe shell32.dll,Control_RunDLL main.cpl @0,1"

[Scheme.Cur]
$scheme_cur

[Scheme.Txt]

[Strings]
CUR_DIR             = "Cursors\\$theme_name"
SCHEME_NAME         = "$theme_name"
$strings
"""
    ),
    "uninstall.bat": Template(
        """@echo off
:: ===========================================================
:: Auto-Generated File
:: ===========================================================
:: This file has been automatically generated by a tool
:: called 'clickgen'. For more information,
:: visit: https://www.github.com/ful1e5/clickgen
::
:: Credit: https://github.com/smit-sms
::         https://github.com/ful1e5/apple_cursor/issues/79
:: ===========================================================

REG DELETE "HKCU\\Control Panel\\Cursors\\Schemes" /v "$theme_name" /f

:: ===============================================================================
:: This enables a popup message box to indicate a user for the operation complete.
:: ===============================================================================
echo x=msgbox("Successfully deleted the cursor!", 0+64, "Cursor") > %tmp%\\tmp.vbs
wscript %tmp%\\tmp.vbs
del %tmp%\\tmp.vbs
"""
    ),
}

# NOTE: DO NOT CHANGE ORDER OF THIS LIST
# https://github.com/ful1e5/Bibata_Cursor/issues/154#issuecomment-1783938013
all_wreg = [
    'HKCU,"Control Panel\\Cursors",Arrow,0x00020000,"%10%\\%CUR_DIR%\\%pointer%"',
    'HKCU,"Control Panel\\Cursors",Help,0x00020000,"%10%\\%CUR_DIR%\\%help%"',
    'HKCU,"Control Panel\\Cursors",AppStarting,0x00020000,"%10%\\%CUR_DIR%\\%work%"',
    'HKCU,"Control Panel\\Cursors",Wait,0x00020000,"%10%\\%CUR_DIR%\\%busy%"',
    'HKCU,"Control Panel\\Cursors",crosshair,0x00020000,"%10%\\%CUR_DIR%\\%cross%"',
    'HKCU,"Control Panel\\Cursors",precisionhair,0x00020000,"%10%\\%CUR_DIR%\\%cross%"',
    'HKCU,"Control Panel\\Cursors",IBeam,0x00020000,"%10%\\%CUR_DIR%\\%text%"',
    'HKCU,"Control Panel\\Cursors",NWPen,0x00020000,"%10%\\%CUR_DIR%\\%handwriting%"',
    'HKCU,"Control Panel\\Cursors",No,0x00020000,"%10%\\%CUR_DIR%\\%unavailable%"',
    'HKCU,"Control Panel\\Cursors",SizeNS,0x00020000,"%10%\\%CUR_DIR%\\%vert%"',
    'HKCU,"Control Panel\\Cursors",SizeWE,0x00020000,"%10%\\%CUR_DIR%\\%horz%"',
    'HKCU,"Control Panel\\Cursors",SizeNWSE,0x00020000,"%10%\\%CUR_DIR%\\%dgn1%"',
    'HKCU,"Control Panel\\Cursors",SizeNESW,0x00020000,"%10%\\%CUR_DIR%\\%dgn2%"',
    'HKCU,"Control Panel\\Cursors",Grab,0x00020000,"%10%\\%CUR_DIR%\\%move%"',
    'HKCU,"Control Panel\\Cursors",SizeAll,0x00020000,"%10%\\%CUR_DIR%\\%move%"',
    'HKCU,"Control Panel\\Cursors",UpArrow,0x00020000,"%10%\\%CUR_DIR%\\%alternate%"',
    'HKCU,"Control Panel\\Cursors",Hand,0x00020000,"%10%\\%CUR_DIR%\\%link%"',
    'HKCU,"Control Panel\\Cursors",Pin,0x00020000,"%10%\\%CUR_DIR%\\%pin%"',
    'HKCU,"Control Panel\\Cursors",Person,0x00020000,"%10%\\%CUR_DIR%\\%person%"',
    'HKCU,"Control Panel\\Cursors",Pan,0x00020000,"%10%\\%CUR_DIR%\\%pan%"',
    'HKCU,"Control Panel\\Cursors",Grabbing,0x00020000,"%10%\\%CUR_DIR%\\%grabbing%"',
    'HKCU,"Control Panel\\Cursors",Zoom-in,0x00020000,"%10%\\%CUR_DIR%\\%zoom-in%"',
    'HKCU,"Control Panel\\Cursors",Zoom-out,0x00020000,"%10%\\%CUR_DIR%\\%zoom-out%"',
]


def pack_win(
    dir: Path,
    theme_name: str,
    comment: str,
    website: Optional[str] = None,
) -> None:
    files: List[Path] = []

    for ext in ("*.ani", "*.cur"):
        for i in sorted(dir.glob(ext)):
            files.append(i)

    sreg, scur, sstr, wreg_list = [], [], [], []

    # Define a custom sorting key function
    def custom_sort_key(file_path):
        stem = file_path.stem.lower()
        for item in all_wreg:
            if f"%{stem}%" in item:
                return all_wreg.index(item)
        return len(all_wreg)

    # Sort files using the custom sorting key
    files = sorted(set(files), key=custom_sort_key)

    for f in files:
        stem = f.stem.lower()
        sreg.append(f"%10%\\%CUR_DIR%\\%{stem}%")
        scur.append(f.name)
        sstr.append(f'{stem}{" "*(20-len(stem))}= "{f.name}"')  # noqa: E226
        wreg_list.extend([item for item in all_wreg if f"%{stem}%" in item])

    scheme_reg = f'"{",".join(sreg)}"'
    scheme_cur = "\n".join(scur)
    strings = "\n".join(sstr)
    wreg = "\n".join(wreg_list)

    for fname, template in FILE_TEMPLETES.items():
        data: str = template.safe_substitute(
            theme_name=f"{theme_name} Cursors",
            comment=comment,
            website=website,
            scheme_reg=scheme_reg,
            scheme_cur=scheme_cur,
            strings=strings,
            wreg=wreg,
        )
        f = dir / fname
        f.write_text(data)
