package com.yuchen.saas.park.api.config.convert;

import com.yuchen.saas.park.api.commons.enums.DoorAccessControlConfigType;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Arrays;

@MappedJdbcTypes({JdbcType.INTEGER})
@MappedTypes({DoorAccessControlConfigType.class})
public class DoorAccessControlConfigTypeTypeHandler extends BaseTypeHandler<DoorAccessControlConfigType> {
    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, DoorAccessControlConfigType parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter.getCode());
    }

    @Override
    public DoorAccessControlConfigType getNullableResult(ResultSet rs, String columnName) throws SQLException {
        return this.getByInt(rs.getInt(columnName));
    }

    @Override
    public DoorAccessControlConfigType getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        return this.getByInt(rs.getInt(columnIndex));
    }

    @Override
    public DoorAccessControlConfigType getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        return this.getByInt(cs.getInt(columnIndex));
    }

    public DoorAccessControlConfigType getByInt(int i) {
        return Arrays.stream(DoorAccessControlConfigType.values()).filter(o -> o.getCode() == i).findFirst().orElseThrow(IllegalAccessError::new);
    }
}