package org.example.Utils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;

public class UrlDecoderUtils {
    /**
     * 与C# HttpUtility.UrlDecode(string)对应，方法名保持一致
     */
    public static String UrlDecode(String str) {
        if (str == null) {
            return null;
        }
        return UrlDecode(str, StandardCharsets.UTF_8);
    }

    /**
     * 与C# HttpUtility.UrlDecode(string, Encoding)对应，方法名保持一致
     */
    public static String UrlDecode(String str, Charset encoding) {
        if (str == null) {
            return null;
        }
        try {
            return URLDecoder.decode(str, encoding.name());
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("不支持的编码格式: " + encoding.name(), e);
        }
    }

    /**
     * 与C# HttpUtility.UrlDecode(byte[])对应，方法名保持一致
     */
    public static String UrlDecode(byte[] bytes, Charset encoding) {
        if (bytes == null) {
            return null;
        }
        return UrlDecode(bytes, 0, bytes.length, encoding);
    }

    /**
     * 与C# HttpUtility.UrlDecode(byte[], int, int, Encoding)对应，方法名保持一致
     */
    public static String UrlDecode(byte[] bytes, int offset, int count, Charset encoding) {
        if (bytes == null) {
            return null;
        }
        String str = new String(bytes, offset, count, encoding);
        return UrlDecode(str, encoding);
    }
}
