package org.exoplatform.cs.service.listener;

import org.exoplatform.commons.utils.CommonsUtils;
import org.exoplatform.forum.common.CommonUtils;
import org.exoplatform.forum.service.Category;
import org.exoplatform.forum.service.DataStorage;
import org.exoplatform.forum.service.Forum;
import org.exoplatform.forum.service.Utils;
import org.exoplatform.services.organization.Group;
import org.exoplatform.services.organization.OrganizationService;
import org.exoplatform.social.core.space.SpaceUtils;
import org.exoplatform.social.core.space.impl.SpaceServiceImpl;
import org.exoplatform.social.core.space.model.Space;
import org.jboss.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import org.exoplatform.container.PortalContainer;
import org.exoplatform.cs.service.CSSpaceService;
import org.exoplatform.social.core.space.SpaceListenerPlugin;
import org.exoplatform.social.core.space.spi.SpaceLifeCycleEvent;

import java.util.Calendar;

import static org.exoplatform.forum.service.Utils.FORUM_SPACE_ID_PREFIX;

public class CSSpaceListener extends SpaceListenerPlugin {
  private static final Logger LOG = LoggerFactory.getLogger(CSSpaceListener.class);

  @Override
  public void spaceAccessEdited(SpaceLifeCycleEvent event) {
  }

  @Override
  public void spaceCreated(SpaceLifeCycleEvent event) {
    DataStorage storage = CommonsUtils.getService(DataStorage.class);
    Space space = event.getSpace();
    String parentGrId = "";
    try {
      OrganizationService service = CommonsUtils.getService(OrganizationService.class);
      Group group = service.getGroupHandler().findGroupById(space.getGroupId());
      parentGrId = group.getParentId();

      String categorySpId = Utils.CATEGORY + parentGrId.replaceAll(CommonUtils.SLASH, CommonUtils.EMPTY_STR);
      Category category = storage.getCategory(categorySpId);
      if (category == null) {
        category = new Category(categorySpId);
        category.setCategoryName(SpaceUtils.SPACE_GROUP.replace(CommonUtils.SLASH, CommonUtils.EMPTY_STR));
        category.setOwner(space.getManagers()[0]);
        category.setCategoryOrder(100l);
        category.setUserPrivate(new String[]{""});
        category.setDescription("All forums from spaces");
        storage.saveCategory(category, true);
      }
      String forumId = FORUM_SPACE_ID_PREFIX + group.getGroupName();
      String groupId = space.getGroupId();
      if (storage.getForum(categorySpId, forumId) == null) {
        String[] roles = new String[] { groupId };

        String[] moderators = new String[] { new StringBuilder(SpaceServiceImpl.MANAGER).append(CommonUtils.COLON)
                .append(groupId).toString() };
        Forum forum = new Forum();
        forum.setOwner(space.getManagers()[0]);
        forum.setId(forumId);
        forum.setForumName(space.getDisplayName());
        forum.setDescription(space.getDescription() == null ? Strings.EMPTY : space.getDescription());
        forum.setModerators(moderators);
        forum.setCreateTopicRole(roles);
        forum.setPoster(roles);
        forum.setViewer(roles);
        forum.setCreatedDate(Calendar.getInstance().getTime());
        storage.saveForum(categorySpId, forum, true);
        storage.saveUserPrivateOfCategory(categorySpId, groupId);
      }
    } catch (Exception e) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Failed to add forum space. " + e.getMessage());
        }
    }
  }

  @Override
  public void spaceRemoved(SpaceLifeCycleEvent event) {
    String spaceType = event.getSpace().getType();
    if (spaceType.equals("CSSpace")) {
      CSSpaceService csSpaceService = PortalContainer.getInstance().getComponentInstanceOfType(CSSpaceService.class);
      try {
        csSpaceService.removeSpace(event.getSpace().getGroupId());
      } catch (Exception e) {
        LOG.error("Error while deleting space" + event.getSpace().getGroupId(), e);
      }
    }
  }

  @Override
  public void applicationActivated(SpaceLifeCycleEvent event) {
  }

  @Override
  public void applicationAdded(SpaceLifeCycleEvent event) {
  }

  @Override
  public void applicationDeactivated(SpaceLifeCycleEvent event) {
  }

  @Override
  public void applicationRemoved(SpaceLifeCycleEvent event) {
  }

  @Override
  public void grantedLead(SpaceLifeCycleEvent event) {
  }

  @Override
  public void joined(SpaceLifeCycleEvent event) {
  }

  @Override
  public void left(SpaceLifeCycleEvent event) {
  }

  @Override
  public void revokedLead(SpaceLifeCycleEvent event) {
  }

  @Override
  public void spaceRenamed(SpaceLifeCycleEvent event) {
  }

  @Override
  public void spaceDescriptionEdited(SpaceLifeCycleEvent event) {
  }

  @Override
  public void spaceAvatarEdited(SpaceLifeCycleEvent event) {
  }

  @Override
  public void addInvitedUser(SpaceLifeCycleEvent event) {
  }

  @Override
  public void addPendingUser(SpaceLifeCycleEvent event) {
  }

  @Override
  public void spaceRegistrationEdited(SpaceLifeCycleEvent event) {

  }

  @Override
  public void spaceBannerEdited(SpaceLifeCycleEvent spaceLifeCycleEvent) {
    
  }

}
