package org.matrix.testNg;

import org.springframework.beans.factory.annotation.Value;

import java.sql.*;
import java.util.*;

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

    ResultSet resultSet;
    ResultSetMetaData resultSetMetaData;

    public DataProviderForDb(String ip, String port, String baseName,
                             String userName, String password, String sql) {
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            String url = String.format("jdbc:mysql://%s:%s/%s" + "?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC", ip, port, baseName);
            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();
        }
    }

}