package com.palacesun.engine.spy;

import com.palacesun.engine.event.CompoundJdbcEventListener;
import com.palacesun.engine.event.DefaultEventListener;
import com.palacesun.engine.event.JdbcEventListener;
import java.util.Iterator;
import java.util.List;
import java.util.ServiceLoader;

public class DefaultJdbcEventListenerFactory implements JdbcEventListenerFactory {
   private static ServiceLoader<JdbcEventListener> jdbcEventListenerServiceLoader = ServiceLoader.load(JdbcEventListener.class, DefaultJdbcEventListenerFactory.class.getClassLoader());
   private static volatile JdbcEventListener jdbcEventListener;

   public JdbcEventListener createJdbcEventListener() {
      if (jdbcEventListener == null) {
         synchronized(DefaultJdbcEventListenerFactory.class) {
            if (jdbcEventListener == null) {
               CompoundJdbcEventListener compoundEventListener = new CompoundJdbcEventListener();
               compoundEventListener.addListener(DefaultEventListener.INSTANCE);
               this.registerEventListenersFromFactories(compoundEventListener);
               this.registerEventListenersFromServiceLoader(compoundEventListener);
               jdbcEventListener = compoundEventListener;
            }
         }
      }

      return jdbcEventListener;
   }

   public static void clearCache() {
      jdbcEventListener = null;
   }

   protected void registerEventListenersFromFactories(CompoundJdbcEventListener compoundEventListener) {
      List<P6Factory> factories = P6ModuleManager.getInstance().getFactories();
      if (factories != null) {
         for(P6Factory factory : factories) {
            JdbcEventListener eventListener = factory.getJdbcEventListener();
            if (eventListener != null) {
               compoundEventListener.addListener(eventListener);
            }
         }
      }

   }

   protected void registerEventListenersFromServiceLoader(CompoundJdbcEventListener compoundEventListener) {
      Iterator<JdbcEventListener> iterator = jdbcEventListenerServiceLoader.iterator();

      while(iterator.hasNext()) {
         compoundEventListener.addListener((JdbcEventListener)iterator.next());
      }

   }
}
