/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this file,
 * You can obtain one at http://mozilla.org/MPL/2.0/. */

package pt.webdetails.cdc;

import java.util.List;
import java.util.Locale;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.platform.api.engine.IPentahoSession;
import org.pentaho.platform.api.engine.IPluginLifecycleListener;
import org.pentaho.platform.api.engine.IUserDetailsRoleListService;
import org.pentaho.platform.api.engine.PluginLifecycleException;
import org.pentaho.platform.engine.core.system.PentahoSystem;
import org.pentaho.platform.engine.core.system.UserSession;
import org.pentaho.platform.plugin.action.mondrian.catalog.MondrianCatalogHelper;

import org.pentaho.platform.engine.security.SecurityHelper;
import org.pentaho.platform.util.messages.LocaleHelper;
import org.springframework.security.Authentication;
import org.springframework.security.GrantedAuthority;
import org.springframework.security.providers.anonymous.AnonymousAuthenticationToken;

/**
 * Responsible for setting up distributed cache from configuration.
 */
public class CdcLifeCycleListener implements IPluginLifecycleListener
{
  
  private static HazelcastManager hazelcastManager = HazelcastManager.INSTANCE;
  
  static Log logger = LogFactory.getLog(CdcLifeCycleListener.class);

  @Override
  public void init() throws PluginLifecycleException
  {
    logger.debug("init");
  }

  @Override
  public void loaded() throws PluginLifecycleException
  {
    logger.debug("CDC loaded.");
    setHazelcastOptionsFromConfig();
    try {
      if (CdcConfig.getConfig().isMondrianCdcEnabled() || ExternalConfigurationsManager.isCdaHazelcastEnabled()){
        
        hazelcastManager.init(CdcConfig.getConfig().getHazelcastConfigFile(), CdcConfig.getConfig().isForceConfig());
        
//        if(CdcConfig.getConfig().isCdaCdcEnabled() && !ExternalConfigurationsManager.isCdaHazelcastEnabled()){
//          logger.info("Hazelcast cache enabled in CDC config but not in CDA, changing CDA settings.");
//          ExternalConfigurationsManager.setCdaHazelcastEnabled(true);
//        }
        
      }
      
      
      //Trying to ensure all locales are covered 
      
      List<String> configuredLocales = CdcConfig.getConfig().getLocales();
      
      Locale[] locales;
      if (configuredLocales.size() == 1 && "all".equals(configuredLocales.get(0)))
        locales = Locale.getAvailableLocales();
      else {
        locales = new Locale[configuredLocales.size()];
        for (int i=0; i < configuredLocales.size(); i++) {
          String[] splitLocale = configuredLocales.get(i).split("_");
          locales[i] = new Locale(splitLocale[0], splitLocale[1]);
        }
      }
     
      for (int i=0; i < locales.length; i++) {
        LocaleHelper.setLocale(locales[i]);
        
        logger.debug("Setting schema cache for locale " + locales[i].toString());
        
        MondrianCatalogHelper.getInstance().listCatalogs(CdcLifeCycleListener.getSessionForCatalogCache(), true);        
        
      }
                  
      
    } catch (Exception e) {
      logger.error(e);
    }

  }
  
  @Override
  public void unLoaded() throws PluginLifecycleException
  {
    logger.debug("CDC Unloading...");
    hazelcastManager.tearDown();
    logger.debug("CDC Unloaded.");
    
  }

  private void setHazelcastOptionsFromConfig(){
    HazelcastManager hazelcastMgr = HazelcastManager.INSTANCE;
    CdcConfig config = CdcConfig.getConfig();
    hazelcastMgr.setDebugMode(config.isDebugMode());
    hazelcastMgr.setLaunchInnerProcess(true);
    hazelcastMgr.setLiteMode(config.isLiteMode());
    hazelcastMgr.setSyncConfig(true);
    hazelcastMgr.setRegisterMondrian(config.isMondrianCdcEnabled());
  }

  
   private static IPentahoSession getSessionForCatalogCache() {     
       return PentahoSystem.get(IPentahoSession.class, "systemStartupSession", null);     
    } 
  
  
}


@@ -485,76 +485,8 @@
 er;%0A
-import org.pentaho.platform.api.engine.IUserDetailsRoleListService;%0A
 impo
@@ -612,68 +612,8 @@
 em;%0A
-import org.pentaho.platform.engine.core.system.UserSession;%0A
 impo
@@ -723,286 +723,34 @@
 orm.
-engine.security.SecurityHelper;%0Aimport org.pentaho.platform.util.messages.LocaleHelper;%0Aimport org.springframework.security.Authentication;%0Aimport org.springframework.security.GrantedAuthority;%0Aimport org.springframework.security.providers.anonymous.AnonymousAuthenticationToken
+util.messages.LocaleHelper
 ;%0A%0A/
@@ -896,18 +896,16 @@
 tener%0A%7B%0A
-  
 %0A  priva
@@ -1415,32 +1415,93 @@
 led())%7B%0A        
+hazelcastManager.setMaster(CdcConfig.getConfig().isMaster());
 %0A        hazelca
@@ -1997,24 +1997,43 @@
 ered %0A      
+//TODO: explain why
 %0A      List%3C
@@ -2127,16 +2127,72 @@
 ocales;%0A
+      Locale originalLocale = LocaleHelper.getLocale();%0A
       if
@@ -2265,16 +2265,18 @@
 get(0)))
+ %7B
 %0A       
@@ -2312,24 +2312,32 @@
 eLocales();%0A
+      %7D%0A
       else %7B
@@ -2609,24 +2609,104 @@
     %7D%0A     %0A
+      logger.debug(%22Setting schema cache for %22 + locales.length + %22 locales.%22);%0A
       for (i
@@ -2788,108 +2788,8 @@
 %5D);%0A
-        %0A        logger.debug(%22Setting schema cache for locale %22 + locales%5Bi%5D.toString());%0A        %0A
     
@@ -2933,27 +2933,118 @@
     
-            %0A      
+logger.debug(%22Reverting to original locale %22 + originalLocale);%0A      LocaleHelper.setLocale(originalLocale);%0A
 %0A   

set back original locale on init so you don't end up with a french pentaho