package com.tsi.common.utils;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;

public class StringUtils {

    private StringUtils() {}

    public static String getString(boolean value) {
        return value ? "1" : "0";
    }

    public static List<String> splitEmpty(String value, String separator) {
        List<String> results = new ArrayList<String>();
        StringTokenizer stringTokenizer = new StringTokenizer(value, separator);
        while (stringTokenizer.hasMoreTokens()) {
            results.add(stringTokenizer.nextToken().trim());
        }
        return results;
    }

    public static List<String> split(String value, String separator) {
        String[] splits = value.split(separator);
        List<String> results = new ArrayList<String>();
        for (int ii = 0; ii < splits.length; ii++) {
            splits[ii] = splits[ii].trim();
            if (!splits[ii].isEmpty()) {
                results.add(splits[ii]);
            }
        }
        return results;
    }

    public static boolean isEmpty(String str) {
        return str == null || str.isEmpty();
    }

    public static boolean isBlank(String s) {
        return s == null || s.trim().isEmpty();
    }

    public static String safeSubstring(String input, int maxBytes) {
        if (input == null || input.isEmpty()) return "";

        byte[] bytes = input.getBytes(StandardCharsets.UTF_8);
        if (bytes.length <= maxBytes) return input;

        int byteCount = 0;
        int charIndex = 0;
        for (char c : input.toCharArray()) {
            int charBytes = String.valueOf(c).getBytes(StandardCharsets.UTF_8).length;
            if (byteCount + charBytes > maxBytes) break;
            byteCount += charBytes;
            charIndex++;
        }

        return input.substring(0, charIndex);
    }

}
