package org.exoplatform.cs.listener;

import java.util.List;


import org.exoplatform.cs.dto.SpaceDTO;
import org.exoplatform.cs.service.CSSpaceService;
import org.exoplatform.cs.service.util.CSUtils;
import org.exoplatform.services.listener.Asynchronous;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.organization.Membership;
import org.exoplatform.services.organization.MembershipEventListener;
import org.exoplatform.social.core.space.model.Space;
import org.exoplatform.social.core.space.spi.SpaceService;

/**
 * Created by eXo Platform SAS.
 *
 * @author Ali Hamdi 
 * @since 16/11/17 11:19
 */
@Asynchronous
public class CSMemebrshipListener extends MembershipEventListener{
  protected static Log log = ExoLogger.getLogger(CSMemebrshipListener.class);

  private CSSpaceService csSpaceService;

  private SpaceService spaceService;

  public CSMemebrshipListener(CSSpaceService csSpaceService, SpaceService spaceService) {
    this.csSpaceService = csSpaceService;
    this.spaceService = spaceService;
  }

  @Override
  public void postSave(Membership m, boolean isNew) throws Exception {
    if(CSUtils.getSupportTeamGroup().equals(m.getGroupId().replaceAll("/",""))) {
      List<SpaceDTO> spaces = csSpaceService.getAllSpaces();
      for(SpaceDTO spaceDTO : spaces) {
        try {
          Space originalSpace = spaceService.getSpaceByGroupId(spaceDTO.getGroupId());
          if(!spaceService.isMember(originalSpace,m.getUserName())) {
            spaceService.addMember(originalSpace, m.getUserName());
          }
        }catch (Exception e){
          log.error("Can not add user {} to the space {}", m.getUserName(), spaceDTO.getName(), e);
        }
      }
      log.info("User {} was added to all customer spaces", m.getUserName());
    }
  }

  @Override
  public void postDelete(Membership m) throws Exception {
    if(CSUtils.getSupportTeamGroup().equals(m.getGroupId().replaceAll("/",""))) {
      List<SpaceDTO> spaces = csSpaceService.getAllSpaces();
      for(SpaceDTO spaceDTO : spaces) {
        try {
          Space originalSpace = spaceService.getSpaceByGroupId(spaceDTO.getGroupId());
          if(spaceService.isMember(originalSpace,m.getUserName())) {
            spaceService.removeMember(originalSpace, m.getUserName());
          }
        }catch (Exception e){
          log.error("Can not remove user {} from the space {}",m.getUserName(), spaceDTO.getName(), e);
        }
      }
      log.info("User {} was removed from all customer spaces", m.getUserName());
    }
  }
}
