package com.zhiqiyun.open.mybatis.typeHandler;

import com.zhiqiyun.open.enmus.IEnum;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

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

/**
 * @author jtoms
 */
public class IEnumTypeHandler<E extends IEnum<Integer>> extends BaseTypeHandler<E> {

    private final Class<E> type;

    public IEnumTypeHandler(Class<E> type) {
        if (type == null) {
            throw new IllegalArgumentException("Type argument cannot be null");
        }
        this.type = type;
    }

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, E parameter, JdbcType jdbcType) throws SQLException {
        ps.setInt(i, parameter.getValue());
    }

    @Override
    public E getNullableResult(ResultSet rs, String columnName) throws SQLException {
        int i = rs.getInt(columnName);
        if (rs.wasNull()) {
            return null;
        } else {
            return this.getEnum(i);
        }
    }

    @Override
    public E getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        int i = rs.getInt(columnIndex);
        if (rs.wasNull()) {
            return null;
        } else {
            return this.getEnum(i);
        }
    }

    @Override
    public E getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        int i = cs.getInt(columnIndex);
        if (cs.wasNull()) {
            return null;
        } else {
            return this.getEnum(i);
        }
    }

    public E getEnum(int value) {
        E[] enums = this.type.getEnumConstants();
        E em = null;
        if (enums != null) {
            for (E e : enums) {
                if (e.getValue() == value) {
                    em = e;
                    break;
                }
            }
        }
        return em;
    }

}
