package com.iqser.red.service.persistence.management.v1.processor.utils;

import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.StandardCharsets;
import java.nio.charset.UnsupportedCharsetException;

import org.apache.commons.lang3.StringUtils;

import com.iqser.red.service.persistence.management.v1.processor.exception.BadRequestException;

import lombok.experimental.UtilityClass;

@UtilityClass
public final class StringEncodingUtils {

    Character COMMA = ',';


    public static String urlEncode(String input) {

        if (input == null) {
            return null;
        }

        var result = new StringBuilder();
        for (var i = 0; i < input.length(); i++) {
            if (StringUtils.isAsciiPrintable(Character.toString(input.charAt(i))) && input.charAt(i) != COMMA) {
                result.append(input.charAt(i));
            } else {
                result.append(URLEncoder.encode(Character.toString(input.charAt(i)), StandardCharsets.UTF_8));
            }
        }
        return result.toString();
    }

    public static Charset resolveCharset(String encoding) {

        try {
            return Charset.forName(encoding);
        } catch (IllegalCharsetNameException e) {
            throw new BadRequestException("Invalid character encoding: " + encoding);
        } catch (UnsupportedCharsetException e) {
            throw new BadRequestException("Unsupported character encoding: " + encoding);
        } catch (IllegalArgumentException e) {
            throw new BadRequestException("Encoding can't be null.");
        }
    }

}
