/*
 * Copyright (C) 2003-2016 eXo Platform SAS.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License
 * as published by the Free Software Foundation; either version 3
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, see<http://www.gnu.org/licenses/>.
 */
package org.exoplatform.cs.service.listener;

import java.util.Calendar;

import javax.jcr.Node;
import javax.jcr.Session;

import org.apache.commons.lang3.StringUtils;

import org.exoplatform.commons.utils.CommonsUtils;
import org.exoplatform.container.PortalContainer;
import org.exoplatform.container.xml.InitParams;
import org.exoplatform.forum.common.CommonUtils;
import org.exoplatform.forum.ext.impl.ForumDataInitialize;
import org.exoplatform.forum.service.*;
import org.exoplatform.services.jcr.RepositoryService;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.social.core.space.SpaceUtils;
import org.exoplatform.social.core.space.model.Space;
import org.exoplatform.social.core.space.spi.SpaceLifeCycleEvent;

public class CSForumDataInitializer extends ForumDataInitialize {

  private static final Log LOG = ExoLogger.getLogger(CSForumDataInitializer.class);

  private String           portletName;

  public CSForumDataInitializer(InitParams params, ForumService forumService) {
    super(params,forumService);
    portletName = params.getValueParam("portletName").getValue();
    if (StringUtils.isBlank(portletName)) {
      LOG.error("Portlet name is Blank. Attention, this listener will not be triggered.");
    }
  }

  @Override
  public void applicationAdded(SpaceLifeCycleEvent event) {
    DataStorage storage = CommonsUtils.getService(DataStorage.class);
    Space space = event.getSpace();
    if (StringUtils.isBlank(portletName) || !portletName.equals(event.getSource()) || space == null) {
      return;
    }
    try {
      String categorySpId = Utils.CATEGORY + SpaceUtils.SPACE_GROUP.replaceAll(CommonUtils.SLASH, CommonUtils.EMPTY_STR);
      String forumId = Utils.FORUM_SPACE_ID_PREFIX + space.getPrettyName();
      super.applicationAdded(event);
      Forum forum = storage.getForum(categorySpId, forumId);

      // FIXME forum created date is null, leads to a null pointer exception
      fixCreatedDate(forum, storage.getWorkspace());

      //forum.setCreateTopicRole(forum.getModerators());

      storage.saveForum(categorySpId, forum, false);
    } catch (Exception e) {
      LOG.warn("Failed to initialize CS Space forum. ", e);
    }
  }

  private void fixCreatedDate(Forum forum, String workspace) throws Exception {
    RepositoryService repoSrv = PortalContainer.getInstance().getComponentInstanceOfType(RepositoryService.class);
    Session systemSession = repoSrv.getCurrentRepository().getSystemSession(workspace);
    Node forumNode = (Node) systemSession.getItem(forum.getPath());
    Calendar createdDate = forumNode.getProperty(ForumNodeTypes.EXO_CREATED_DATE).getDate();
    forum.setCreatedDate(createdDate.getTime());
    if(systemSession != null) {
      systemSession.logout();
    } 
  }

}
