package com.aip.gateway.api.utils;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.StringTokenizer;

public class StringUtils {

    public static String randomStr(int length) {
        Random random = new Random();
        StringBuilder str = new StringBuilder();
        for (int ii = 0; ii < length; ii++) {
            int choice = random.nextInt(3);
            switch(choice) {
                case 0:
                    str.append((char)(random.nextInt(25)+97));
                    break;
                case 1:
                    str.append((char)(random.nextInt(25) +65));
                    break;
                case 2:
                    str.append((char)(random.nextInt(10) +48));
                    break;
                default:
                    break;
            }
        }
        return str.toString();
    }

    public static List<String> split(String value, String delim) {

        List<String> list = new ArrayList<String>();

        StringTokenizer stringTokenizer = new StringTokenizer(value, delim);
        while (stringTokenizer.hasMoreTokens()) {
            list.add(stringTokenizer.nextToken().trim());
        }
        return list;
    }

    public static boolean isBlank(String str) {
        if (str == null || "".equals(str.trim())) {
            return true;
        }
        return false;
    }

    public static boolean isNotBlank(String str) {
        return !isBlank(str);
    }

    public static String subString(String str, int length) {
        if (isBlank(str)) {
            return "";
        }
        return str.substring(0, Math.min(str.length(), length));
    }

    public static String firstUppercase(String str) {
        char baseChar = str.charAt(0);
        char updatedChar = Character.toUpperCase(baseChar);
        if (baseChar == updatedChar) {
            return str;
        }
        char[] chars = str.toCharArray();
        chars[0] = updatedChar;
        return new String(chars, 0, chars.length);
    }

    public static String firstLowercase(String str) {
        char baseChar = str.charAt(0);
        char updatedChar = Character.toLowerCase(baseChar);
        if (baseChar == updatedChar) {
            return str;
        }
        char[] chars = str.toCharArray();
        chars[0] = updatedChar;
        return new String(chars, 0, chars.length);
    }

    public static String escapeSpecialCharacters(String data) {
        String escapedData = data.replaceAll("\\R", " ");   // carriage return
        if (data.contains(",") || data.contains("\"") || data.contains("'")) {  // , " '
            String tmpData = data.replace("\"", "\"\"");
            escapedData = "\"" + tmpData + "\"";
        }
        return escapedData;
    }
}
