package org.implab.gradle.common.core.lang;

import java.util.regex.Pattern;

import org.eclipse.jdt.annotation.NonNullByDefault;
import org.gradle.api.provider.Provider;

@NonNullByDefault
public class Strings {

    private static final Pattern firstLetter = Pattern.compile("^\\w");

    public static String capitalize(String string) {
        return string == null ? null
                : string.length() == 0 ? string
                        : firstLetter.matcher(string).replaceFirst(m -> m.group().toUpperCase());
    }

    public static String toCamelCase(String name) {
        if (name == null || name.isEmpty())
            return name;
        StringBuilder out = new StringBuilder(name.length());
        boolean up = false;
        boolean first = true;
        for (int i = 0; i < name.length(); i++) {
            char c = name.charAt(i);
            switch (c) {
                case '-', '_', ' ', '.' -> up = true;
                default -> {
                    out.append(
                            first ? Character.toLowerCase(c)
                                    : up ? Character.toUpperCase(c): c);
                    up = false;
                    first = false;
                }
            }
        }
        return out.toString();
    }

    public static void argumentNotNullOrEmpty(String value, String argumentName) {
        if (value == null || value.length() == 0)
            throw new IllegalArgumentException(String.format("Argument %s can't be null or empty", argumentName));
    }

    public static String asString(Object value) {
        if (value == null)
            return null;
        if (value instanceof Provider<?> provider)
            return asString(provider.get());
        else
            return value.toString();
    }
}
