package com.ease.gsms.server.model.util;

import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@JsonSerialize(using = IDEnumSerializer.class)
@JsonDeserialize(using = IDEnumDeserializer.class)
public interface IDEnum {

    Map<Class<? extends IDEnum>, Map<Integer, ? extends IDEnum>> map = new ConcurrentHashMap<>();

    @SuppressWarnings("unchecked")
    static <T extends IDEnum> T byId(Class<T> idEnumClass, int id) {

        if (!map.containsKey(idEnumClass)) {

            map.put(
                    idEnumClass,
                    new HashMap<Integer, T>(){{
                        try {
                            T[] values = (T[]) idEnumClass.getMethod("values").invoke(null);
                            Arrays.stream(values).forEach(possibility -> put(possibility.getId(), possibility));
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }
                    }}
            );

        }

        return (T) map.get(idEnumClass).get(id);
    }


    int getId();

    String name();

}
