package zmo.technology.lite.core;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public abstract class ZeroProcessor {

    protected ZeroRequestGuider guider;

    public void setGuider(ZeroRequestGuider guider) {
        this.guider = guider;
    }

    public ZeroRequestGuider getGuider() {
        return guider;
    }

    public Connection getConnection() throws SQLException {
        return guider.getConnection();
    }

    private Statement statement;

    public Statement getStatement() throws SQLException {
        if (statement == null)
            statement = guider.getConnection().createStatement();
        return statement;
    }

    private Map<String, PreparedStatement> preparedStatements;

    public void registeyPreparedStatement(String preparedSQL) throws SQLException {
        preparedStatements.put(preparedSQL, guider.getConnection().prepareStatement(preparedSQL));
    }

    public boolean existsPreparedStatement(String features) throws SQLException {
        return preparedStatements.containsKey(features);
    }

    public PreparedStatement preparedStatement(String features) throws SQLException {
        return preparedStatements.get(features);
    }

    public void release() throws SQLException {
        if (statement != null)
            statement.close();
        for (String key : preparedStatements.keySet())
            preparedStatements.remove(key).close();
    }

    protected ZeroProcessor(ZeroRequestGuider guider) {
        super();
        this.guider = guider;
        this.preparedStatements = new ConcurrentHashMap<String, PreparedStatement>();
    }
}
