/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package uchile.wic.santander;

import java.io.IOException;
import java.sql.*;
import org.json.JSONObject;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

/**
 *
 * @author ricoc_000
 */
public class Extractor implements Job {

    @Override
    public void execute(JobExecutionContext jec) throws JobExecutionException {

        Long id;
        String text;
        double polaridad;
        int count = 0;

        try {
            // Conectarse al DSA
            Connection conn = Helpers.GetConnectionPostgresql("santander");
            Statement stt = conn.createStatement();
            String sql = "SELECT data FROM dsa_tweet "
                    + "WHERE snap > NOW() - INTERVAL '200 minutes'";
            ResultSet rs = stt.executeQuery(sql);
            
            System.out.println("Empezando la iteración");
            while (rs.next()) {
                JSONObject jason = new JSONObject(rs.getString(1));
                id = jason.getLong("id");
                System.out.println("Rescatando id");
                text = jason.getString("text");
                System.out.println(text);
                polaridad = Helpers.GetPolarityFromCorpus(text);

                sql = "INSERT INTO fact (idtwitter, text, polaridad) "
                        + "VALUES(?,?,?)";
                PreparedStatement ppd = conn.prepareStatement(sql);
                ppd.setLong(1, id);
                ppd.setString(2, text);
                ppd.setDouble(3, polaridad);

                count++;
            }
        } catch (SQLException sqle) {
            sqle.printStackTrace();
        } catch (IOException ex) {
            ex.printStackTrace();
        }

        System.out.println("Estamos listos con " + count + " tweets");
    }
}
