package com.its.api.its.model.enums.converter;

import com.its.api.its.model.enums.ICodeValue;
import lombok.extern.slf4j.Slf4j;

import javax.persistence.AttributeConverter;
import java.util.EnumSet;
import java.util.NoSuchElementException;

@Slf4j
public class CodeValueConverter <E extends Enum<E> & ICodeValue> implements AttributeConverter<E, String> {

    private Class<E> clz;

    public CodeValueConverter(Class<E> enumClass) {
        this.clz = enumClass;
    }

    @Override
    public String convertToDatabaseColumn(E e) {
        return e.getCode();
    }

    @Override
    public E convertToEntityAttribute(String code) {
        return EnumSet.allOf(this.clz).stream()
                .filter(e->e.getCode().equals(code))
                .findAny()
                .orElseThrow(()-> new NoSuchElementException());
    }

}
