package org.matrix.testNg;

import java.sql.*;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * @author mry
 */
public class DataProviderForDb implements Iterator<Object[]> {

    ResultSet resultSet;
    ResultSetMetaData resultSetMetaData;

    public DataProviderForDb(String driver, String url
            , String userName, String password, String sql) {
        try {
            Class.forName(driver);
            Connection conn = DriverManager.getConnection(url, userName, password);
            Statement createStatement = conn.createStatement();

            resultSet = createStatement.executeQuery(sql);
            resultSetMetaData = resultSet.getMetaData();
        } catch (ClassNotFoundException | SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public boolean hasNext() {
        boolean flag = false;
        try {
            flag = resultSet.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }

    @Override
    public Object[] next() {
        @SuppressWarnings(value = "all")
        Map<String, String> data = new HashMap<>();
        try {
            for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
                data.put(resultSetMetaData.getColumnName(i), resultSet.getString(i));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        Object[] objects = new Object[1];
        objects[0] = data;
        return objects;
    }

    @Override
    public void remove() {
        try {
            resultSet.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

}