package com.ym.mec.collectfee.common.dao;

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

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

/**
 * 枚举类转换器
 * @author pengdc
 */
@SuppressWarnings("rawtypes")
public class IntEnumTypeHandler extends BaseTypeHandler<BaseIntEnum> {

	private Class<BaseIntEnum> type;

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

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, BaseIntEnum parameter, JdbcType jdbcType) throws SQLException {
		if (jdbcType == null) {
			ps.setString(i, String.valueOf(parameter.getCode()));
		} else {
			ps.setObject(i, parameter.getCode(), jdbcType.TYPE_CODE); // see r3589
		}
	}

	@Override
	public BaseIntEnum getNullableResult(ResultSet rs, String columnName) throws SQLException {
		return convert(rs.getInt(columnName));
	}

	@Override
	public BaseIntEnum getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
		return convert(rs.getInt(columnIndex));
	}

	@Override
	public BaseIntEnum getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
		return convert(cs.getInt(columnIndex));
	}

	public BaseIntEnum convert(int code) {
		for (BaseIntEnum enumBaseInterface : type.getEnumConstants()) {
			if (enumBaseInterface.getCode() == code) {
				return enumBaseInterface;
			}
		}
		return null;
	}
}