package com.ease.gsms.server.repositories.util;

import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.support.KeyHolder;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public abstract class BatchPreparedStatementSetterWithKeyHolder<T> implements BatchPreparedStatementSetter {

    private final List<T> items;

    public BatchPreparedStatementSetterWithKeyHolder(List<T> items) {
        this.items = items;
    }

    @Override
    public void setValues(PreparedStatement ps, int i) throws SQLException {
        setValues(ps, items.get(i));
    }

    @Override
    public final int getBatchSize() {
        return items.size();
    }

    public void setPrimaryKey(KeyHolder keyHolder) {
        List<Map<String, Object>> keys = keyHolder.getKeyList();
        for (int i = 0, len = keys.size(); i < len; i++) {
            setPrimaryKey(keys.get(i), items.get(i));
        }
    }

    protected abstract void setValues(PreparedStatement ps, T bean) throws SQLException;

    protected abstract void setPrimaryKey(Map<String, Object> primaryKey, T bean);

}