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.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

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

	private Class<BaseStringEnum> type;

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

	@Override
	public void setNonNullParameter(PreparedStatement ps, int i, BaseStringEnum parameter, JdbcType jdbcType) throws SQLException {
		if (jdbcType != null) {
			ps.setString(i, parameter.getName() + "");
		} else {
			ps.setObject(i, parameter.getName());
		}
	}

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

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

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

	public BaseStringEnum convert(String name) {
		for (BaseStringEnum enumBaseInterface : type.getEnumConstants()) {
			if (StringUtils.equals(StringUtils.chomp(name), enumBaseInterface.getName())) {
				return enumBaseInterface;
			}
		}
		return null;
	}

}