//
//  SystemConfig.swift
//  sdlan
//
//  Created by 安礼成 on 2024/6/3.
//

import Foundation

struct SystemConfig {
    // 版本设置
    static let version: Int = 1
    
    static let version_name = "1.1"
    
    static let serverHost = "punchnet.s5s8.com"
    
    // stun探测辅助服务器ip
    static let stunAssistHost = "punchnet.s5s8.com"
    
    static func getOptions(networkId: UInt32, networkDomain: String, ip: String, maskLen: UInt8, accessToken: String, identityId: UInt32, hostname: String, noticePort: Int) -> [String: NSObject]? {
        guard let serverIp = DNSResolver.resolveAddrInfos(serverHost).first else {
            return nil
        }
        
        let clientId = getClientId()
        let mac = getMacAddress()
        
        let options =  [
            "version": version as NSObject,
            "client_id": clientId as NSObject,
            "access_token": accessToken as NSObject,
            "identity_id": identityId as NSObject,
            "server_ip": "118.178.229.213" as NSObject,
            "stun_assist_ip": "118.178.229.213" as NSObject,
            "hostname": hostname as NSObject,
            "notice_port": noticePort as NSObject,
            "network_address": [
                "network_id": networkId as NSObject,
                "ip": ip as NSObject,
                "mask_len": maskLen as NSObject,
                "mac": mac as NSObject,
                "network_domain": networkDomain as NSObject
            ] as NSObject
        ]
        
        return options
    }
    
    public static func getClientId() -> String {
        let userDefaults = UserDefaults.standard
        if let uuid = userDefaults.value(forKey: "gClientId") as? String {
            return uuid
        } else {
            let uuid = UUID().uuidString.replacingOccurrences(of: "-", with: "").lowercased()
            userDefaults.setValue(uuid, forKey: "gClientId")
            
            return uuid
        }
    }
    
    // 获取mac地址
    public static func getMacAddress() -> Data {
        let key = "gMacAddress2"
        
        let userDefaults = UserDefaults.standard
        if let mac = userDefaults.value(forKey: key) as? Data {
            return mac
        }
        else {
            let mac = generateMacAddress()
            userDefaults.setValue(mac, forKey: key)
            
            return mac
        }
    }
    
    public static func macAddressString(mac: Data, separator: String = ":") -> String {
        return mac.map { String(format: "%02X", $0) }
            .joined(separator: separator)
    }
    
    // 随机生成mac地址
    private static func generateMacAddress() -> Data {
        var macAddress = [UInt8](repeating: 0, count: 6)
        for i in 0..<6 {
            macAddress[i] = UInt8.random(in: 0...255)
        }
        
        return Data(macAddress)
    }
    
}
