package com.apobates.forum.utils.lang;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * 枚举的扩展结构
 * 
 * @author xiaofanku
 * @since 20190305
 */
public interface EnumArchitecture {

	int getSymbol();

	String getTitle();

	static Map<Integer, String> getInstance(Class<?> instance) {
		boolean isInstance = false;
		Class<?>[] dec = instance.getInterfaces();
		for (Class<?> decFace : dec) {
			if (EnumArchitecture.class.isAssignableFrom(decFace)) {
				isInstance = true;
				break;
			}
		}
		if (!isInstance) {
			return Collections.emptyMap();
		}
		Map<Integer, String> data = new HashMap<>();
		Object[] ins = instance.getEnumConstants();
		for (Object tmp : ins) {
			EnumArchitecture B = (EnumArchitecture) tmp;
			data.put(B.getSymbol(), B.getTitle());
		}
		return data;
	}

	@SuppressWarnings("unchecked")
	static <T> Optional<T> getInstance(int symbol, Class<T> instance) {
		boolean isInstance = false;
		Class<?>[] dec = instance.getInterfaces();
		for (Class<?> decFace : dec) {
			if (EnumArchitecture.class.isAssignableFrom(decFace)) {
				isInstance = true;
				break;
			}
		}
		if (!isInstance) {
			return Optional.empty();
		}
		T data = null;
		Object[] ins = instance.getEnumConstants();
		for (Object tmp : ins) {
			EnumArchitecture B = (EnumArchitecture) tmp;
			if (B.getSymbol() == symbol) {
				data = (T)B;
				break;
			}
		}
		return Optional.ofNullable(data);
	}
}
