package com.changhu.common.db;

import cn.hutool.core.util.ObjectUtil;
import com.changhu.common.cache.GlobalCacheManager;
import com.changhu.common.exception.MessageException;
import com.changhu.common.pojo.vo.SelectNodeVo;

import java.util.Map;

/**
 * author: luozhun
 * desc: BaseEnum
 * createTime: 2023/8/16 17:38
 */
public interface BaseEnum<V> {

    /**
     * 获取值
     *
     * @return V
     */
    V getValue();

    /**
     * 获取文本
     *
     * @return string
     */
    String getLabel();

    @SuppressWarnings("unchecked")
    static <P, T extends BaseEnum<P>> T valueOf(Class<? extends BaseEnum<P>> enumType, P code) {
        Map<BaseEnum<?>, SelectNodeVo<?>> nodeVoMap = GlobalCacheManager.ENUM_CACHE.get(enumType);
        for (Map.Entry<BaseEnum<?>, SelectNodeVo<?>> mapEntry : nodeVoMap.entrySet()) {
            if (ObjectUtil.equals(code, mapEntry.getValue().getValue())) {
                return (T) mapEntry.getKey();
            }
        }
        throw new MessageException("不存在值为:{} 的【{}】对象!", code.toString(), enumType.componentType().getSimpleName());
    }

    @SuppressWarnings("unchecked")
    default SelectNodeVo<V> serializer() {
        Map<BaseEnum<?>, SelectNodeVo<?>> map = GlobalCacheManager.ENUM_CACHE.get(this.getClass());
        if (map != null) {
            return (SelectNodeVo<V>) map.get(this);
        }
        return null;
    }

}
