package io.papermc.paper.configuration.type;

import java.lang.reflect.Type;
import java.util.OptionalInt;
import java.util.function.Predicate;
import org.apache.commons.lang3.math.NumberUtils;
import org.spongepowered.configurate.serialize.ScalarSerializer;
import org.spongepowered.configurate.serialize.SerializationException;

public record IntOrDefault(OptionalInt value) {
    private static final String DEFAULT_VALUE = "default";
    public static final IntOrDefault USE_DEFAULT = new IntOrDefault(OptionalInt.empty());
    public static final ScalarSerializer<IntOrDefault> SERIALIZER = new Serializer();

    public int or(final int fallback) {
        return this.value.orElse(fallback);
    }

    private static final class Serializer extends ScalarSerializer<IntOrDefault> {
        Serializer() {
            super(IntOrDefault.class);
        }

        @Override
        public IntOrDefault deserialize(final Type type, final Object obj) throws SerializationException {
            if (obj instanceof String string) {
                if (DEFAULT_VALUE.equalsIgnoreCase(string)) {
                    return USE_DEFAULT;
                }
                if (NumberUtils.isParsable(string)) {
                    return new IntOrDefault(OptionalInt.of(Integer.parseInt(string)));
                }
            } else if (obj instanceof Integer num) {
                return new IntOrDefault(OptionalInt.of(num));
            }
            throw new SerializationException(obj + "(" + type + ") is not a integer or '" + DEFAULT_VALUE + "'");
        }

        @Override
        protected Object serialize(final IntOrDefault item, final Predicate<Class<?>> typeSupported) {
            final OptionalInt value = item.value();
            if (value.isPresent()) {
                return value.getAsInt();
            } else {
                return DEFAULT_VALUE;
            }
        }
    }
}
