package net.ranides.assira.reflection.util;

import lombok.experimental.UtilityClass;
import net.ranides.assira.generic.Ref;
import net.ranides.assira.reflection.IMethod;
import net.ranides.assira.reflection.IReflectiveException;
import net.ranides.assira.text.StringUtils;

@UtilityClass
public class MemberUtils {

    public static String asPropertyName(String name) {
        if(name.startsWith("is") ) {
            return StringUtils.uncapitalize(name.substring(2));
        }
        if( name.startsWith("get") ) {
            return StringUtils.uncapitalize(name.substring(3));
        }
        if( name.startsWith("set") ) {
            return StringUtils.uncapitalize(name.substring(3));
        }
        throw new IReflectiveException("Unknown property pattern: " + name);
    }

    public static IMethod asGetter(IMethod method) {
        if(method.isGetter()) {
            return method;
        }
        if(method.isSetter()) {
            Ref<IMethod> primary = method.parent().method(method.name().replaceAll("^set", "get"));
            if(primary.isPresent()) {
                return primary.get();
            }
            if(method.returns().isBoolean()) {
                Ref<IMethod> secondary = method.parent().method(method.name().replaceAll("^set", "is"));
                if(secondary.isPresent()) {
                    return secondary.get();
                }
            }
        }
        throw new IReflectiveException("Unknown property pattern: " + method);
    }

    public static IMethod asSetter(IMethod method) {
        if(method.isSetter()) {
            return method;
        }
        if(method.isGetter()) {
            Ref<IMethod> primary = method.parent().method(method.name().replaceAll("^(get|is)", "set"));
            if(primary.isPresent()) {
                return primary.get();
            }
        }
        throw new IReflectiveException("Unknown property pattern: " + method);
    }
}
