package org.kravemir.lightvalue.naming;

import org.kravemir.lightvalue.model.PropertyDef;

import java.util.Arrays;
import java.util.stream.Collectors;

public class DefaultNameProvider implements NameProvider {

    private Pluralizer pluralizer = new Pluralizer();

    @Override
    public String getAccessorName(PropertyDef propertyDef) {
        String accessor = toCamelCase(propertyDef.getName());

        if(propertyDef.isRepeated()) {
            accessor = pluralizer.pluralize(accessor);
        }

        return accessor;
    }

    @Override
    public String getSingularAccessorName(PropertyDef propertyDef) {
        return toCamelCase(propertyDef.getName());
    }

    @Override
    public  String getVariableName(PropertyDef propertyDef) {
        String name = "m_" + firstToLowerCase(toCamelCase(propertyDef.getName()));

        if(propertyDef.isRepeated()) {
            if (name.charAt(name.length() -1) == 's') {
                name += "es";
            } else {
                name += "s";
            }
        }

        return name;
    }

    private static String toCamelCase(String s){
        return Arrays.stream(s.split("_"))
                .map(DefaultNameProvider::firstToUpperCase)
                .collect(Collectors.joining(""));
    }

    private static String firstToLowerCase(String s) {
        return s.substring(0, 1).toLowerCase() + s.substring(1);
    }

    private static String firstToUpperCase(String s) {
        return s.substring(0, 1).toUpperCase() + s.substring(1);
    }
}
