package com.queplix.tools.fkchecker.kernel.sources;

import com.queplix.tools.fkchecker.kernel.exceptions.SourceException;
import com.queplix.tools.fkchecker.kernel.types.ForeignKey;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author dmitry.antonov
 */
public abstract class AbstractDBSource implements ForeignKeysSource {

    private Connection con;

    private final String url;
    private final String user;
    private final String passwd;
    private final String driverName;
    protected ResultSet fkeys;

    public AbstractDBSource(Properties properties) {
        url = properties.getProperty("url");
        user = properties.getProperty("user");
        passwd = properties.getProperty("password");
        driverName = properties.getProperty("driver");
    }

    public final void closeSource() {
        try {
            if (con != null) {
                con.close();
            }
        } catch (SQLException e) {
            throw new RuntimeException("Couldn't close DB connection", e);
        }
    }

    public final void openSource() {
        try {
            Class.forName(driverName);
            con = DriverManager.getConnection(url, user, passwd);
            prepareParsing(con);
        } catch (Exception e) {
            throw new RuntimeException("Couldn't open DB source", e);
        }
    }

    protected abstract void prepareParsing(Connection con) throws SQLException;

    public final boolean hasNextForeignKey() throws SourceException {
        try {
            return hasNext();
        }
        catch(SQLException e) {
            throw new SourceException(e);
        }
    }

    protected abstract boolean hasNext() throws SQLException;

    public ForeignKey nextForeignKey() {
        try {
            return nextForeignKey(con);
        } catch (SQLException e) {
            throw new RuntimeException("Couldn't get next foreign key", e);
        }
    }

    protected abstract ForeignKey nextForeignKey(Connection con) throws SQLException;

}
