package cc.smtweb.framework.core.common;

import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by Akmm at 2017/5/3 17:25
 * 枚举基类
 */
public abstract class AbstractEnum<K, V extends AbstractEnum.EnumBean> {
    public Map<K, V> mapAll = new LinkedHashMap<>();

    public V addEnum(K value, String name) {
        final V bean = buildBean(value, name);
        mapAll.put(value, bean);
        return bean;
    }

    public void delEnum(K value) {
        mapAll.remove(value);
    }

    protected abstract V buildBean(K value, String name);

    protected Object getSqlValue(V pbs) {
        return pbs.value;
    }

    //根据值获取对象
    public V getByValue(K value) {
        V v = mapAll.get(value);
        if (v != null) return v;
        return getDefault();
    }

    public V getByName(String name) {
        for (V bs : mapAll.values()) {
            if (bs.name.equals(name)) return bs;
        }
        return null;
    }

    //根据value获取name
    public String getName(K value) {
        V bean = getByValue(value);
        return bean != null ? bean.name: "";
    }

    //默认值
    public V getDefault() {
        return null;
    }

    //所有枚举定义
    public Collection<V> values() {
        return mapAll.values();
    }

    public boolean contains(K value) {
        return mapAll.containsKey(value);
    }

    //遍历枚举类
    public void doEnum(IEnumWorker<V> worker) {
        for (V bean : mapAll.values()) {
            worker.work(bean);
        }
    }

    /**
     * 枚举值对象定义
     */
    public static class EnumBean<T> {
        public T value;
        public String name;

        public EnumBean(T value, String name) {
            this.value = value;
            this.name = name;
        }
    }

    /**
     * Int、Text 枚举值对象定义
     */
    public static class IntEnumBean extends EnumBean<Integer> {
        public IntEnumBean(Integer value, String name) {
            super(value, name);
        }
    }

    /**
     * Str、Text 枚举值对象定义
     */
    public static class StrEnumBean extends EnumBean<String> {
        public StrEnumBean(String value, String name) {
            super(value, name);
        }
    }

    //枚举回调类
    public interface IEnumWorker<V extends EnumBean> {
        public void work(V enumBean);
    }
}
