package com.loafle.overflow.crawler.sql;


import com.loafle.overflow.crawler.Crawler;
import com.loafle.overflow.crawler.config.Config;
import com.loafle.overflow.crawler.config.Item;
import com.loafle.overflow.crawler.config.Query;
import com.loafle.overflow.crawler.result.*;

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

/**
 * Created by insanity on 17. 4. 11.
 */
public class SQLCrawler extends Crawler {

    public SQLCrawler() {}

    @Override
    public Object getInternal(Config config) {
        return getMetrics(config);
    }


    private Object getMetrics(Config config) {

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;

        String url = (String)config.getTarget().getAuth().get("url");
        String id =  (String)config.getTarget().getAuth().get("id");
        String pw =  (String)config.getTarget().getAuth().get("pw");

        List<OFResultSet> resultSets = new ArrayList<>();

        try {
            conn = DriverManager.getConnection(url, id, pw);
            stmt = conn.createStatement();

            for (Item item : config.getItems()) {

                OFResultSet resultSet = OFResultSetRow.newInstance(item);
                Map<String,Integer> meta = resultSet.getMeta();

                rs = stmt.executeQuery((String)item.getQueryInfo().getQuery());

                while(rs.next()) {
                    List<String> row =  new ArrayList<>(Arrays.asList(new String[meta.size()]));
                    for (Map.Entry<String, Integer> info : meta.entrySet()) {
                        String data = rs.getString(info.getKey());
                        data = data.trim();
                        row.set(info.getValue().intValue(),data);
                    }
                    resultSet.addRow(row);
                }

                resultSets.add(resultSet);
                rs.close();
            }
            return resultSets;

        } catch (Exception e) {
            e.printStackTrace();
            new Exception(e.getMessage()).printStackTrace();
        } finally {
            if (conn != null) {try {conn.close();} catch (SQLException e) {e.printStackTrace();}}
            if (rs != null) {try {rs.close();} catch (SQLException e) {e.printStackTrace();}}
            if (stmt != null) {try {stmt.close();} catch (SQLException e) {e.printStackTrace();}}
        }
        return null;
    }

}
