/*
 * 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.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Date;
import java.util.List;
import org.json.JSONObject;
import org.postgresql.util.PGobject;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.TwitterObjectFactory;
import twitter4j.conf.ConfigurationBuilder;
import twitter4j.json.DataObjectFactory;

/**
 *
 * @author ricoc_000
 */
public class Rester {

// Credenciales   
    private static String Ckey = "8B78rPejHGAdNbArYRn2tPpVw";
    private static String CkeySecret = "U8rP92ONHRIoP82JTMNsmuuuqFR3F9eFXRDrn73lWBUUNoAILF";
    private static String AToken = "409619735-zyatT1vf09BwNGxlOaEhqeU9YauPVZbn7Q1GqMTS";
    private static String AtokenSecret = "3GVVhYedKk2Qc4pj0R0A5JSc0ooom69Fw9fM7I9eO1tHT";

    // ConexiÃ³n con la base de datos
    private static Connection conn = Helpers.GetConnectionPostgresql("santander");
    private static PreparedStatement insertar, insert_user;
    private static String sql;
    
    // Otras
    private static String name, screen, id, sexo;

    private static Date fecha;

    //main
    public static void main(String[] args) {

        // Configuration 
        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true).setOAuthConsumerKey(Ckey)
                .setOAuthConsumerSecret(CkeySecret)
                .setOAuthAccessToken(AToken)
                .setOAuthAccessTokenSecret(AtokenSecret)
                .setJSONStoreEnabled(true);

        Twitter twitter = new TwitterFactory(cb.build()).getInstance();

        try {

            Query query = new Query("workcafe");
            QueryResult result;
            int Count = 0;
            do {
                result = twitter.search(query);
                List<Status> tweets = result.getTweets();
                for (Status tweet : tweets) {
                    //System.out.println("@" + tweet.getUser().getScreenName() + ":" + tweet.getText() + ", creado el:" + tweet.getCreatedAt());
//                    String statusJson = DataObjectFactory.getRawJSON(tweet);
//                    System.out.println(statusJson);
                    JSONObject jobject = new JSONObject(TwitterObjectFactory.getRawJSON(tweet));
                    JSONObject juser = jobject.getJSONObject("user");

                    try {
                        PGobject dataObject = new PGobject();
                        dataObject.setType("timestamp");
                        dataObject.setValue(jobject.getString("created_at"));
                        sql = "INSERT INTO tweet2 (texto, timestamp) "
                                + "VALUES (?,?)";
                        insertar = conn.prepareStatement(sql);
                        insertar.setString(1, tweet.getText());
                        insertar.setObject(2, dataObject);
                        insertar.execute();
                    } catch (SQLException sqle) {
                        sqle.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    
                    try {                        
                        name = juser.getString("name");
                        screen = juser.getString("screen_name");
                        id = juser.getString("id_str");
                        sexo = Integer.toString(Helpers.GetSexo(name, screen));
                        System.out.println("Name y Screen : "+name +" "+ screen +". Sexo:"+sexo);
                        sql = "INSERT INTO users (name, screen, id, sexo) "
                                + "VALUES (?,?,?,?)";
                        insert_user = conn.prepareStatement(sql);
                        insert_user.setString(1, name);
                        insert_user.setString(2, screen);
                        insert_user.setString(3, id);
                        insert_user.setString(4, sexo);
                        insert_user.execute();              
                    } catch (SQLException sqle) {
                        sqle.printStackTrace();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    Count++;
                }
            } while ((query = result.nextQuery()) != null);
            System.out.println(Count);
            System.exit(0);

        } catch (TwitterException te) {
            te.printStackTrace();
            System.out.println("Failed to search tweets: " + te.getMessage());
            System.exit(-1);
        }
    }
}
