package com.loafle.overflow.crawler.sql;

import com.loafle.overflow.crawler.Crawler;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

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

    public SQLCrawler() {}

    @Override
    public Object getInternal(Map<String, Object> config) {
        return getMetrics(config);
    }


    private Object getMetrics(Map<String, Object> config) {

        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            conn = DriverManager.getConnection(
                    (String)config.get("url"),
                    (String)config.get("user"),
                    (String)config.get("pw"));
            stmt = conn.createStatement();

            rs = stmt.executeQuery((String)config.get("query"));

            ResultSetMetaData md = rs.getMetaData();
            int cnt = md.getColumnCount();

            List<DBMetaInfo> metaList = new ArrayList<DBMetaInfo>();

            for (int i =0 ; i < cnt ; ++i) {
                DBMetaInfo o = new DBMetaInfo();
                o.setName(md.getColumnName(i+1));
                metaList.add(o);
            }

            List<Map<String, String>> datas = new ArrayList<Map<String, String>>();
            while(rs.next()){
                Map<String, String> row = new HashMap<String, String>();
                for (DBMetaInfo o : metaList) {
                    row.put(o.getName(), rs.getString(o.getName()));
                }
                datas.add(row);
            }

            return datas;

        } catch (Exception e) {
            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;
    }

}
