//
//  ShortCuts.swift
//  SpeedKeys
//
//  Created by Jose Polo Ramos on 3/2/25.
//
import SwiftUI
/// Type Definition for the ShortCut
struct ShortCuts:CustomStringConvertible {
    var hasCommand:Bool
    var hasControl:Bool
    var hasOption:Bool
    var hasShift:Bool
    var key:Int64 = 0
    
    init(event: CGEvent){
        key = event.getIntegerValueField(.keyboardEventKeycode)
        hasCommand = event.flags.contains(.maskCommand)
        hasControl = event.flags.contains(.maskControl)
        hasOption = event.flags.contains(.maskAlternate)
        hasShift = event.flags.contains(.maskShift)
    }

    
    // Static dictionary for faster key lookups
    private static let keyMap: [Int64: String] = [
        0: "a",  11: "b",   8: "c",   2: "d",   14: "e",
        3: "f",   5: "g",   4: "h",  34: "i",   38: "j",
        40: "k", 37: "l",  46: "m",  45: "n",   31: "o",
        35: "p", 12: "q",  15: "r",   1: "s",   17: "t",
        32: "u",  9: "v",  13: "w",   7: "x",   16: "y",
        6: "z"
    ]
    
    func matchKey(fromInt int: Int64) -> String {
        return Self.keyMap[int] ?? ""
    }
    

    
    
    // Optimized string construction with capacity reservation
    public var description: String {
        var mods = [String]()
        mods.reserveCapacity(5) // Pre-allocate for maximum possible modifiers
        
        if hasCommand { mods.append("⌘") }
        if hasOption { mods.append("⌥") }
        if hasShift { mods.append("⇧") }
        if hasControl { mods.append("⌃") }
        
        let key = matchKey(fromInt: key)
        if !key.isEmpty {
            mods.append(key)
        }
        return mods.joined(separator: "+")

    }
}
