package ru.yandex.autodoc.common.util.enums;

import java.util.Collection;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;

/**
 * @author avhaliullin
 */
public class IntEnumResolver<T extends Enum<T> & IntEnum> extends AbstractEnumResolver<T, IntEnumResolver<T>> implements IIntEnumResolver<T> {
    protected final Map<Integer, T> id2Value;

    public IntEnumResolver(Class<T> enumClass, T defaultValue) {
        this(enumClass, defaultValue, EnumSet.allOf(enumClass));
    }

    public IntEnumResolver(Class<T> enumClass, T defaultValue, Collection<T> universe) {
        super(enumClass, defaultValue, universe);

        id2Value = new HashMap<>();
        for (T val : valuesSet) {
            id2Value.put(getId(val), val);
        }
    }

    @Override
    protected IntEnumResolver<T> create(Class<T> enumClass, T defaultValue, Collection<T> universe) {
        return new IntEnumResolver<>(enumClass, defaultValue, universe);
    }

    @Override
    public Integer getId(T value) {
        return value.getId();
    }

    @Override
    public int getPrimitiveId(T value) {
        Integer res = getId(value);
        if (res == null) {
            throw new IllegalArgumentException("Enum: " + String.valueOf(value) + " not found in universe of this resolver: [" + join(valuesSet, ", "));
        }
        return res;
    }

    @Override
    public T getById(int id) {
        return id2Value.get(id);
    }

    @Override
    public String getName(T val) {
        if (val == null) {
            return null;
        }
        return val.name();
    }
}
