package com.yonge.cooleshow.common.config;

import com.yonge.toolset.base.enums.BaseEnum;
import org.springframework.core.convert.converter.Converter;

public class EnumConverter<T extends BaseEnum<?, ?>> implements Converter<Object, T> {

	private Class<T> enumType;

	public EnumConverter(Class<T> enumType) {
		this.enumType = enumType;
	}

	@Override
	public T convert(Object source) {
		return getEnum(enumType, source);
	}

	private T getEnum(Class<T> targerType, Object source) {
		if(null == source){
			return null;
		}
		for (T en : targerType.getEnumConstants()) {
			if (en.getCode() instanceof Integer) {
				try {
					if (en.getCode().equals(Integer.parseInt(source.toString()))) {
						return en;
					}
				}catch (Exception e){}
			} else {
				if (source.toString().equals(String.valueOf(en.getCode()))) {
					return en;
				}
			}
		}
		return null;
	}
}
