//
//  vpn_Base64Decoder.swift
//  HYVvppn
//
//  Created by Mr. Liu on 2025/1/18.
//


import Foundation

class vpn_Base64Decoder {
    // Base64解码表
    static let base64DecodingTable: [Int8] = {
        var table = [Int8](repeating: -2, count: 256)
        for (index, char) in "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".utf8.enumerated() {
            table[Int(char)] = Int8(index)
        }
        table[61] = -1 // '=' ASCII值为61
        return table
    }()

    /// 解码Base64字符串为Data
    static func dataWithBase64EncodedString(_ base64EncodedString: String) -> Data? {
        let length = base64EncodedString.count
        let utf8String = Array(base64EncodedString.utf8)

        guard !utf8String.isEmpty else {
            return nil
        }

        // 去掉尾部的 '='
        var trimmedLength = length
        while trimmedLength > 0 && utf8String[trimmedLength - 1] == 61 { // '=' 的 ASCII 值是 61
            trimmedLength -= 1
        }

        let outputLength = trimmedLength * 3 / 4
        var output = [UInt8](repeating: 0, count: outputLength)

        var inputPoint = 0
        var outputPoint = 0

        while inputPoint < trimmedLength {
            guard let i0 = decodeCharacter(utf8String[inputPoint]),
                  let i1 = decodeCharacter(utf8String[inputPoint + 1]) else {
                return nil
            }

            let i2 = inputPoint + 2 < trimmedLength ? decodeCharacter(utf8String[inputPoint + 2]) ?? 0 : 0
            let i3 = inputPoint + 3 < trimmedLength ? decodeCharacter(utf8String[inputPoint + 3]) ?? 0 : 0

            // 修复负值的问题，确保使用UInt8来处理
            output[outputPoint] = UInt8((Int(i0) << 2) | (Int(i1) >> 4))
            outputPoint += 1

            if outputPoint < outputLength {
                output[outputPoint] = UInt8(((Int(i1) & 0xF) << 4) | (Int(i2) >> 2))
                outputPoint += 1
            }

            if outputPoint < outputLength {
                output[outputPoint] = UInt8(((Int(i2) & 0x3) << 6) | Int(i3))
                outputPoint += 1
            }

            inputPoint += 4
        }

        return Data(output)
    }

    /// 解码单个字符为对应的值
    private static func decodeCharacter(_ char: UInt8) -> Int8? {
        let decoded = base64DecodingTable[Int(char)]
        return decoded >= 0 ? decoded : nil
    }
}
