package com.tykj.dev.device.confirmcheck.common;

import javax.persistence.AttributeConverter;
import javax.persistence.Converter;
import java.util.stream.Stream;

/**
 * CheckTypeConvert.
 *
 * @author Matrix <xhyrzldf@gmail.com>
 * @since 2020/10/26 at 2:36 下午
 */
@Converter(autoApply = true)
public class CheckTypeConvert implements AttributeConverter<CheckType, Integer> {
    /**
     * Converts the value stored in the entity attribute into the
     * data representation to be stored in the database.
     *
     * @param attribute the entity attribute value to be converted
     * @return the converted data to be stored in the database
     * column
     */
    @Override
    public Integer convertToDatabaseColumn(CheckType attribute) {
        if (attribute == null) {
            return null;
        }

        return attribute.getId();
    }

    /**
     * Converts the data stored in the database column into the
     * value to be stored in the entity attribute.
     * Note that it is the responsibility of the converter writer to
     * specify the correct <code>dbData</code> type for the corresponding
     * column for use by the JDBC driver: i.e., persistence providers are
     * not expected to do such type conversion.
     *
     * @param dbData the data from the database column to be
     *               converted
     * @return the converted value to be stored in the entity
     * attribute
     */
    @Override
    public CheckType convertToEntityAttribute(Integer dbData) {
        if (dbData == null) {
            return null;
        }
        return Stream.of(CheckType.values())
                .filter(t -> t.getId().equals(dbData))
                .findFirst()
                .orElseThrow(IllegalArgumentException::new);
    }
}
