package com.k_int.webapp.helpers;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import org.hibernate.SessionFactory;
import org.hibernate.Session;
import org.hibernate.Query;
import org.hibernate.Transaction;
import org.hibernate.HibernateException;

import javax.servlet.http.HttpServletRequest;
import org.springframework.orm.hibernate3.SessionFactoryUtils;

import com.k_int.sql.data_dictionary.*;
import java.util.List;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import com.k_int.sql.data_dictionary.*;

// Taken from JNDI sample
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.Binding;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import java.util.Hashtable;

@Component
public class ConfigManager {

  private static Log log = LogFactory.getLog(ConfigManager.class);

  @Autowired
  @Qualifier(value="IdentSessionFactory")
  private SessionFactory factory = null;

  @Autowired
  @Qualifier(value="jdbcctx")
  private Context jdbc_context = null;

  private java.util.Map<String,DataSourceInfo> registered_data_sources = new java.util.HashMap<String,DataSourceInfo>();
  public ConfigManager() {
  }

  public java.util.Map<String,DataSourceInfo> getDataSourceInfo() {
    return registered_data_sources;
  }

  @PostConstruct
  private void init() {
    // Load any already existing Dictionaries
    List<com.k_int.sql.config.JDBCDataSource> sources = null;

    if ( factory != null ) {
      Session sess = null;
      try {
        sess = factory.openSession();
        org.hibernate.Query q = sess.createQuery("select x from com.k_int.sql.config.JDBCDataSource x");
        for ( java.util.Iterator i = q.iterate(); i.hasNext(); ) {
          com.k_int.sql.config.JDBCDataSource ds = (com.k_int.sql.config.JDBCDataSource) i.next();
          log.debug("Adding "+ds.getDatasourceIdentifier());
          com.k_int.sql.data_dictionary.Dictionary dict = null;
          try {
            dict = ds.getDictionary();
          }
          catch ( com.k_int.sql.data_dictionary.PersistenceException pe ) {
            log.error("Problem converting jdbc config to dictionary",pe);
          }
          registered_data_sources.put(ds.getDatasourceIdentifier(),new DataSourceInfo(ds.getDatasourceIdentifier(), dict));
        }
      } catch (HibernateException he ) {
        log.error("[firstrun:1] Problem with resource action",he);
      } catch (Exception e ) {
        log.error("[firstrun:1]Problem with resource action",e);
      } finally {
        log.debug("Populate sources returned "+sources);
        sess.close();
      }
    }
    else {
      log.error("No Factory available");
    }

    try {
      processJDBCBindings();
    }
    catch ( javax.naming.NamingException ne ) {
      log.error("Error trying to obtain JNDI JDBC Resources", ne);
    }
  }

  public void processJDBCBindings() throws javax.naming.NamingException {
    if ( jdbc_context != null ) {
      NamingEnumeration ne = jdbc_context.listBindings("");
      while (ne.hasMore()) {
          Binding binding = (Binding)ne.next();
          log.debug( binding.getName() + " " + binding.getObject());
      }
    }
  }
}
