package it.integry.integrywmsnative.core.utility;

import android.text.Html;
import android.text.Spanned;

import androidx.annotation.StringRes;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by GiuseppeS on 07/03/2018.
 */

public class UtilityString {

    public static boolean isNullOrEmpty(String stringToCheck){
        return stringToCheck == null || stringToCheck.trim().length() == 0;
    }

    public static String isNull(String stringToCheck, String alternativeString){
        return isNullOrEmpty(stringToCheck) ? alternativeString : stringToCheck;
    }

    public static String empty2null(String stringToCheck) {
        return (stringToCheck == null || stringToCheck.trim().length() == 0) ? null : stringToCheck.trim();
    }

    public static String capitalizeWords(String capString){
        StringBuffer capBuffer = new StringBuffer();
        Matcher capMatcher = Pattern.compile("([a-z])([a-z]*)", Pattern.CASE_INSENSITIVE).matcher(capString);
        while (capMatcher.find()){
            capMatcher.appendReplacement(capBuffer, capMatcher.group(1).toUpperCase() + capMatcher.group(2).toLowerCase());
        }

        return capMatcher.appendTail(capBuffer).toString();
    }

    public static String toCamelCase(String input) {
        if(UtilityString.isNullOrEmpty(input)) return input;

        String tmp = "";

        tmp += String.valueOf(input.charAt(0)).toUpperCase();

        if(input.length() > 1) {
            tmp += input.substring(1).toLowerCase();
        }

        return tmp;
    }

    public static String mid(String string, Integer start) {
        return mid(string, start, 0);
    }

    public static String mid(String string, Integer start, Integer length){
        String value = "";
        if(start <= string.length()) {
            if(length == 0){
                length = string.length() - start + 1;
            } else if (length > string.length() - start){
                length = string.length() - start + 1;
            }
            value = string.substring(start - 1, start + length - 1).trim();
        }
        return value;
    }

    public static Spanned formatHtmlString(String format, String... params){
        return Html.fromHtml(String.format(format, (Object[]) params));
    }

    public static Spanned formatHtmlStringFromResId(@StringRes int stringId, String... params){
        return Html.fromHtml(String.format(UtilityResources.getString(stringId), (Object[]) params));
    }


    public static boolean equalsIgnoreCase(String val1, String val2) {
        return (val1 == null && val2 == null) ||
                (val1 != null && val1.equalsIgnoreCase(val2));
    }

}
