package org.exoplatform.cs.portlet.common;

import java.util.Enumeration;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

import juzu.Response;
import juzu.impl.common.JSON;

import org.exoplatform.forum.common.UserHelper;
import org.exoplatform.portal.application.PortalRequestContext;
import org.exoplatform.portal.mop.SiteType;
import org.exoplatform.portal.webui.util.Util;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.organization.User;
import org.exoplatform.services.security.ConversationState;
import org.exoplatform.services.security.IdentityConstants;
import org.exoplatform.web.CacheUserProfileFilter;

public abstract class CSControllerBase {

  // Don't use inject to not get the merge of all resource bundles
  // @Inject
  ResourceBundle bundle;

  public Response getBundle(Locale locale) {
    try {
      if (bundle == null || (bundle.getLocale() != null && !bundle.getLocale().equals(locale))){
        bundle = getResourceBundle(locale);
      }
      JSON data = new JSON();
      Enumeration<String> enumeration = getResourceBundle().getKeys();
      while (enumeration.hasMoreElements()) {
        String key = (String) enumeration.nextElement();
        try {
          data.set(key.replaceAll("(.*)\\.", ""), getResourceBundle().getObject(key));
        } catch (MissingResourceException e) {
          // Nothing to do, this happens sometimes
        }
      }
      return Response.ok(data.toString()).withHeader("Cache-Control", "max-age=864000");
    } catch (Throwable e) {
      getLogger().error("error while getting categories", e);
      return Response.status(500);
    }
  }

  public String getCurrentSpaceId() {
    String spaceGroupId = null;
    PortalRequestContext requestContext = Util.getPortalRequestContext();
    if (requestContext != null) {
      if (requestContext.getSiteType().equals(SiteType.GROUP) && requestContext.getSiteName().startsWith("/spaces")) {
        spaceGroupId = requestContext.getSiteName();
      }
    }
    return spaceGroupId;
  }

  public abstract Log getLogger();

  protected User getCurrentUser() throws Exception {
    if (ConversationState.getCurrent() == null || ConversationState.getCurrent().getIdentity() == null
        || ConversationState.getCurrent().getIdentity().getUserId() == null
        || ConversationState.getCurrent().getIdentity().getUserId().equals(IdentityConstants.SYSTEM)) {
      throw new IllegalStateException("Current user not found.");
    }
    User user = (User) ConversationState.getCurrent().getAttribute(CacheUserProfileFilter.USER_PROFILE);
    if (user == null) {
      String userId = ConversationState.getCurrent().getIdentity().getUserId();
      user = UserHelper.getUserByUserId(userId);
    }
    return user;
  }


  /**
   * Checks if the current user is a customer spaces manager
   * @return boolean
   */
  protected boolean isCSManager(){
     return true;
  }

  protected ResourceBundle getResourceBundle(Locale locale) {
    return bundle = ResourceBundle.getBundle("locale.portlet.customer-space", locale, this.getClass().getClassLoader());
  }

  protected ResourceBundle getResourceBundle() {
    if (bundle == null) {
      bundle = getResourceBundle(PortalRequestContext.getCurrentInstance().getLocale());
    }
    return bundle;
  }

}
