package notify;

import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import retin.Commons;

class Listener extends Thread {

    private String notifyName;
    private Connection conn;
    private org.postgresql.PGConnection pgconn;

    public boolean stop; // this is the way to stop the thread

    Listener(Connection conn, String nameOfTheNotify) throws SQLException {
        this.conn = conn;
        this.pgconn = (org.postgresql.PGConnection) conn;
        this.notifyName = nameOfTheNotify;

        Statement stmt = conn.createStatement();
        stmt.execute("LISTEN " + notifyName);
        stmt.close();

        stop = false;
    }

    public void run() {

        while (true) {
            try {
                // once a time issue a dummy query to contact the backend
                Statement stmt = conn.createStatement();
                stmt.executeQuery("SELECT 1");
                stmt.close();

                // and receive any pending notifications.
                org.postgresql.PGNotification notifications[] = pgconn.getNotifications();
                if (notifications != null) {
                    for (int i = 0; i < notifications.length; i++) {
                        System.out.println("Got notification: " + notifications[i].getName());
                    }
                }
                else {
                    System.out.println("Got bullshit");
                }

                // wait a while before checking again for new notifications
                Thread.sleep(500);

            } catch (SQLException sqle) {
                Logger.getLogger(Commons.class.getName()).log(Level.SEVERE, "Listener.run", sqle.toString()) ;
                // sqle.printStackTrace();
            } catch (InterruptedException ie) {
                Logger.getLogger(Commons.class.getName()).log(Level.INFO, "Listener.run", ie.toString()) ;
                // ie.printStackTrace();
            }
        }
    }
}
