package org.exoplatform.cs.service.util;

import java.util.Arrays;
import java.util.List;


import org.exoplatform.commons.utils.ListAccess;
import org.exoplatform.commons.utils.PropertyManager;
import org.exoplatform.container.PortalContainer;
import org.exoplatform.cs.listener.ForumListener;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.organization.OrganizationService;
import org.exoplatform.services.organization.User;
import org.exoplatform.services.security.ConversationState;
import org.exoplatform.services.security.Identity;

/**
 * Created by IntelliJ IDEA.
 * User: ali
 * Date: 30/01/17
 * Time: 17:55
 */
public class CSUtils {
  private static final Log LOG = ExoLogger.getLogger(ForumListener.class);

  private static final String SUPPORT_GROUP_NAME_CONFIGURATION = "exo.addon.cs.support.group.name";

  public static List<User> getSupportMembers() throws Exception {
    return getGroupMembers(getSupportTeamGroup());
  }

  /**
   * Get the group ID for the support team
   * @return
   */
  public static String getSupportTeamGroup() {
    String groupId = PropertyManager.getProperty(SUPPORT_GROUP_NAME_CONFIGURATION);
    if (groupId == null || groupId.isEmpty()){
      groupId = "support-team";
    }
    return groupId;
  }


  public static List<User> getGroupMembers(String groupId) throws Exception {
    PortalContainer container = PortalContainer.getInstance();
    OrganizationService organizationService = container.getComponentInstanceOfType(OrganizationService.class);
    ListAccess<User> engSupportList = organizationService.getUserHandler().findUsersByGroupId(groupId);
    User[] users = engSupportList.load(0, engSupportList.getSize());
    return Arrays.asList(users);
  }

  public static boolean isMemberof(String user, String groupId) {
    PortalContainer container = PortalContainer.getInstance();
    OrganizationService organizationService = container.getComponentInstanceOfType(OrganizationService.class);
    try {
      if(organizationService.getMembershipHandler().findMembershipsByUserAndGroup(user,groupId).size() > 0){
        return true;
      }
    } catch (Exception e) {
      LOG.error("Can not check the membership of {} in group {}", user, groupId, e);
      return false;
    }
    return false;
  }


  public static Boolean canManage() {
    Identity currentId = ConversationState.getCurrent().getIdentity();
    if(currentId.isMemberOf("/"+getSupportTeamGroup())||currentId.isMemberOf("/platform/administrators")) return true;
    return false;
  }
}
