package com.its.op.entity.domain.converter;

import com.its.op.entity.domain.ICodeValue;
import lombok.extern.slf4j.Slf4j;

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

@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) throws NoSuchElementException {
        Optional<E> data = EnumSet.allOf(this.clz).stream()
                .filter(e->e.getCode().equals(code))
                .findAny();
        if (data.isPresent()) {
            return data.get();
        }
        else {
            throw new NoSuchElementException("데이터가 존재하지 않습니다: " + code);
        }
//        return EnumSet.allOf(this.clz).stream()
//                .filter(e->e.getCode().equals(code))
//                .findAny()
//                .orElseThrow(()-> new NoSuchElementException());
    }

}
