// Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/DatabaseException.java
// public class DatabaseException extends RuntimeException {
// 
// 
//     private static final long serialVersionUID = 4421127305934584766L;
// 
//     //force creation with a message
//     private DatabaseException() {
// 
//     }
// 
//     public DatabaseException(final String message) {
//         super(message);
//     }
// 
//     public DatabaseException(final String message, final Throwable t) {
//         super(message, t);
//     }
// }
// 
// Path: notifications/src/main/java/space/npstr/sqlsauce/notifications/exceptions/LoggingNsExceptionHandler.java
// public class LoggingNsExceptionHandler implements NsExceptionHandler {
// 
//     private final Logger logger;
// 
//     public LoggingNsExceptionHandler(Logger log) {
//         this.logger = log;
//     }
// 
//     @Override
//     public void handleNotificationServiceException(Exception e) {
//         logger.error("Notification Service internal exception", e);
//     }
// 
//     @Override
//     public void handleListenerException(Exception e) {
//         logger.error("Uncaught notification listener exception", e);
//     }
// }
// 
// Path: notifications/src/main/java/space/npstr/sqlsauce/notifications/exceptions/NsExceptionHandler.java
// public interface NsExceptionHandler {
//     /**
//      * Any exceptions, most notably all kinds of SQL exceptions will be passed in here.
//      */
//     void handleNotificationServiceException(Exception e);
// 
//     /**
//      * Any uncaught exceptions from calling {@link NotificationListener#notif} will be passed in here.
//      */
//     void handleListenerException(Exception e);
// }


import org.postgresql.PGNotification;
import org.postgresql.jdbc.PgConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import space.npstr.sqlsauce.DatabaseException;
import space.npstr.sqlsauce.notifications.exceptions.LoggingNsExceptionHandler;
import space.npstr.sqlsauce.notifications.exceptions.NsExceptionHandler;
import javax.annotation.Nullable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*
 * MIT License
 *
 * Copyright (c) 2017-2018, Dennis Neufeld
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package space.npstr.sqlsauce.notifications;




/**
 * Created by napster on 06.01.18.
 * <p>
 * This class supports Postgres' LISTEN / NOTIFY feature, mostly the LISTENs (NOTIFYs are easy, just shoot a query at the DB).
 * NOTIFY can be called on any database connection, but you can also use the built in method of this class.
 * <p>
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * ATTENTION: We can't use prepared statements for the queries issueing the LISTENs and UNLISTENs, so the channel names
 * need to be checked by the code calling the methods of these class for their legitimacy. Do not allow these to be set
 * by any user values ever or else sql injections might happen.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * <p>
 * This class creates a single connection to the database. We cannot use a pooled connection, or integrate this feature
 * with a whole pool without a lot of hassle, as LISTENs and UNLISTENs would need to be executed on each connection all
 * the time. Given this and connections being a costly resource, you are encouraged, but not required, to use a single
 * object of this class in your application to register all your listeners with.
 * <p>
 * todo try async registering of listeners while listening to notifications
 */
public class NotificationService {

    private static final Logger log = LoggerFactory.getLogger(NotificationService.class);

    //todo is there a better way to synchronize / thread safety?
    //current thread safety design synchronizes on the listeners object whenever the Map or any of the Sets of its
    //values are accessed
    private final Map<String, Set<NotificationListener>> listeners = new HashMap<>();

    private final Connection connection;              //connection that we are listening on

    private final ExecutorService exec;                 //runs the main loop
// Path: sqlsauce-core/src/main/java/space/npstr/sqlsauce/DatabaseException.java
// public class DatabaseException extends RuntimeException {
// 
// 
//     private static final long serialVersionUID = 4421127305934584766L;
// 
//     //force creation with a message
//     private DatabaseException() {
// 
//     }
// 
//     public DatabaseException(final String message) {
//         super(message);
//     }
// 
//     public DatabaseException(final String message, final Throwable t) {
//         super(message, t);
//     }
// }
// 
// Path: notifications/src/main/java/space/npstr/sqlsauce/notifications/exceptions/LoggingNsExceptionHandler.java
// public class LoggingNsExceptionHandler implements NsExceptionHandler {
// 
//     private final Logger logger;
// 
//     public LoggingNsExceptionHandler(Logger log) {
//         this.logger = log;
//     }
// 
//     @Override
//     public void handleNotificationServiceException(Exception e) {
//         logger.error("Notification Service internal exception", e);
//     }
// 
//     @Override
//     public void handleListenerException(Exception e) {
//         logger.error("Uncaught notification listener exception", e);
//     }
// }
// 
// Path: notifications/src/main/java/space/npstr/sqlsauce/notifications/exceptions/NsExceptionHandler.java
// public interface NsExceptionHandler {
//     /**
//      * Any exceptions, most notably all kinds of SQL exceptions will be passed in here.
//      */
//     void handleNotificationServiceException(Exception e);
// 
//     /**
//      * Any uncaught exceptions from calling {@link NotificationListener#notif} will be passed in here.
//      */
//     void handleListenerException(Exception e);
// }


// Path: notifications/src/main/java/space/npstr/sqlsauce/notifications/NotificationService.java
import org.postgresql.PGNotification;
import org.postgresql.jdbc.PgConnection;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import space.npstr.sqlsauce.DatabaseException;
import space.npstr.sqlsauce.notifications.exceptions.LoggingNsExceptionHandler;
import space.npstr.sqlsauce.notifications.exceptions.NsExceptionHandler;
import javax.annotation.Nullable;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/*
 * MIT License
 *
 * Copyright (c) 2017-2018, Dennis Neufeld
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

package space.npstr.sqlsauce.notifications;




/**
 * Created by napster on 06.01.18.
 * <p>
 * This class supports Postgres' LISTEN / NOTIFY feature, mostly the LISTENs (NOTIFYs are easy, just shoot a query at the DB).
 * NOTIFY can be called on any database connection, but you can also use the built in method of this class.
 * <p>
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * ATTENTION: We can't use prepared statements for the queries issueing the LISTENs and UNLISTENs, so the channel names
 * need to be checked by the code calling the methods of these class for their legitimacy. Do not allow these to be set
 * by any user values ever or else sql injections might happen.
 * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * <p>
 * This class creates a single connection to the database. We cannot use a pooled connection, or integrate this feature
 * with a whole pool without a lot of hassle, as LISTENs and UNLISTENs would need to be executed on each connection all
 * the time. Given this and connections being a costly resource, you are encouraged, but not required, to use a single
 * object of this class in your application to register all your listeners with.
 * <p>
 * todo try async registering of listeners while listening to notifications
 */
public class NotificationService {

    private static final Logger log = LoggerFactory.getLogger(NotificationService.class);

    //todo is there a better way to synchronize / thread safety?
    //current thread safety design synchronizes on the listeners object whenever the Map or any of the Sets of its
    //values are accessed
    private final Map<String, Set<NotificationListener>> listeners = new HashMap<>();

    private final Connection connection;              //connection that we are listening on

    private final ExecutorService exec;                 //runs the main loop
    private final NsExceptionHandler exceptionHandler;    //handles all exceptions after successful init