package com.keao.edu.common.dal;

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

import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import com.keao.edu.common.enums.BaseEnum;

/**
 * 枚举类转换器
 */
@SuppressWarnings("rawtypes")
public class CustomEnumTypeHandler extends BaseTypeHandler<BaseEnum> {

	private Class<BaseEnum> type;

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

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, BaseEnum parameter, JdbcType jdbcType) throws SQLException {
		ps.setObject(i, parameter.getCode());
	}

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

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

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

	public BaseEnum convert(Object name) {
		if (name == null || StringUtils.isBlank(name.toString())) {
			return null;
		}
		Object code = null;
		for (BaseEnum enumBaseInterface : type.getEnumConstants()) {

			code = enumBaseInterface.getCode();

			if (code instanceof Integer) {
				if ((int) code == Integer.parseInt(name.toString())) {
					return enumBaseInterface;
				}
			} else {
				if (code.equals(name)) {
					return enumBaseInterface;
				}
			}
		}
		return null;
	}

}