package com.ruoyi.common.enums.serializer;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.enums.IIntegerEnum;
import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;

@Component
public class EnumConvertFactory implements ConverterFactory<String, IIntegerEnum<Integer>> {


    @Override
    public <T extends IIntegerEnum<Integer>> Converter<String, T> getConverter(Class<T> targetType) {
        return new IntegerToEnum(targetType);
    }

    public static class IntegerToEnum<E extends IIntegerEnum<Integer>> implements Converter<String, E> {

        private final Class<E> targetType;

        public IntegerToEnum(Class<E> targetType) {
            this.targetType = targetType;
        }

        @Override
        public E convert(String source) {
            if (!ObjectUtil.isNotEmpty(source)) {
                return null;
            }
            return (E) EnumConvertFactory.getEnum(this.targetType, Integer.valueOf(source));
        }
    }

    public static <E extends IIntegerEnum<Integer>> E  getEnum(Class<E> targetType, Integer source) {
        for (E  constant : targetType.getEnumConstants()) {
            if(source.equals(constant.getCode()))
            {
                return constant;
            }
        }
        return null;
    }
}
