package org.exoplatform.cs.listener;

import java.util.Calendar;
import java.util.List;


import org.apache.commons.lang3.StringUtils;
import org.exoplatform.commons.api.notification.NotificationContext;
import org.exoplatform.commons.api.notification.model.PluginKey;
import org.exoplatform.commons.notification.impl.NotificationContextImpl;
import org.exoplatform.container.xml.InitParams;
import org.exoplatform.cs.dao.LogDAO;
import org.exoplatform.cs.dao.TopicDAO;
import org.exoplatform.cs.dto.IssueType;
import org.exoplatform.cs.dto.LogType;
import org.exoplatform.cs.entity.LogEntity;
import org.exoplatform.cs.entity.TopicEntity;
import org.exoplatform.cs.integration.notification.CSAddPostPlugin;
import org.exoplatform.cs.integration.notification.CSPrivatePostPlugin;
import org.exoplatform.cs.service.CSConstants;
import org.exoplatform.cs.service.util.CSUtils;
import org.exoplatform.forum.service.Category;
import org.exoplatform.forum.service.DataStorage;
import org.exoplatform.forum.service.Forum;
import org.exoplatform.forum.service.ForumEventListener;
import org.exoplatform.forum.service.MessageBuilder;
import org.exoplatform.forum.service.Post;
import org.exoplatform.forum.service.Topic;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.organization.User;

import static org.exoplatform.cs.service.CSSpaceService.CUSTOMERS_GROUP;

/**
 * Created by IntelliJ IDEA.
 * User: ali
 * Date: 16/01/17
 * Time: 16:26
 */
public class ForumListener extends ForumEventListener {
  private static final Log LOG = ExoLogger.getLogger(ForumListener.class);
  private static final String SUPPORT_GROUP_NAME_CONFIGURATION = "support.group.name";
  private static final String ALL_EMPLOYEE_GROUP_NAME_CONFIGURATION = "all.employee.group.name";
  private TopicDAO topicDAO;
  private LogDAO logDAO;
  private DataStorage dataStorage;
  private String support_group_name;
  private String all_employees_group_name;
  private String customerGroupName;


  public ForumListener(InitParams initParams,TopicDAO topicDAO, DataStorage dataStorage, LogDAO logDAO) {
    this.topicDAO = topicDAO;
    this.logDAO = logDAO;
    this.dataStorage = dataStorage;
    if(initParams.getValueParam(SUPPORT_GROUP_NAME_CONFIGURATION) != null){
      this.support_group_name = initParams.getValueParam(SUPPORT_GROUP_NAME_CONFIGURATION).getValue();
    }
    if(initParams.getValueParam(ALL_EMPLOYEE_GROUP_NAME_CONFIGURATION) != null){
      this.all_employees_group_name = initParams.getValueParam(ALL_EMPLOYEE_GROUP_NAME_CONFIGURATION).getValue();
    }
    customerGroupName = System.getProperty(CUSTOMERS_GROUP);
    if(StringUtils.isBlank(customerGroupName)){
      this.customerGroupName = "customers";
    }
  }

  @Override
  public void addTopic(Topic topic) {

  }

  @Override
  public void updateTopic(Topic topic) {
    if(topic.getIsClosed()){
      TopicEntity ticket = topicDAO.find(topic.getId());
      if(ticket != null){
        ticket.setStatus(CSConstants.STATUS_CLOSED);
        topicDAO.update(ticket);
      }
    }
  }

  @Override
  public void updateTopics(List<Topic> topics, boolean isLock) {

  }

  @Override
  public void moveTopic(Topic topic, String toCategoryName, String toForumName) {

  }

  @Override
  public void movePost(List<Post> posts, List<String> srcPostActivityIds, String desTopicPath) {

  }

  @Override
  public void mergeTopic(Topic newTopic, String removeActivityId1, String removeActivityId2) {

  }

  @Override
  public void splitTopic(Topic newTopic, Topic splitedTopic, String removeActivityId) {

  }

  @Override
  public void addPost(Post post) {
    String topicID = post.getTopicId();
    TopicEntity topicEntity = topicDAO.find(topicID);
    if (topicEntity != null && !IssueType.PRODUCT.equals(topicEntity.getType())) {
      topicEntity.setUpdateDate(Calendar.getInstance());
      topicDAO.update(topicEntity);
      LogType type = LogType.TICKET_COMMENTED_BY_SUPPORT;
      if(CSUtils.isMemberof(post.getOwner(),customerGroupName)){
        type = LogType.TICKET_COMMENTED_BY_CUSTOMER;
      }
      TopicEntity ticket = topicDAO.find(post.getTopicId());
      LogEntity messagePostedLog = new LogEntity(type,post.getOwner(),Calendar.getInstance(),null,null,ticket,null,null,ticket.getSpace().getGroupId());
      logDAO.create(messagePostedLog);

      NotificationContext ctx = NotificationContextImpl.cloneInstance().append(CSAddPostPlugin.TICKET, topicEntity).append(CSAddPostPlugin.POST, post.getMessage()).append(CSAddPostPlugin.POSTER, post.getOwner());
      ctx.getNotificationExecutor().with(ctx.makeCommand(PluginKey.key(CSAddPostPlugin.ID))).execute(ctx);
    }
  }

  @Override
  public void addPrivatePost(Post post) {
    try {
      TopicEntity topic = topicDAO.find(post.getTopicId());
      if (topic != null && !IssueType.PRODUCT.equals(topic.getType())) {
        List<User> supportMembers = CSUtils.getGroupMembers(all_employees_group_name);
        String[] userPrivate = supportMembers.stream().map(User::getUserName).toArray(String[]::new);
        post.setUserPrivate(userPrivate);
        post.setMessage("<div class=\"alert alert-warning\" id=\"\">" + post.getMessage() + "</div>");
        dataStorage.savePost(post.getCategoryId(), post.getForumId(), post.getTopicId(), post, false, new MessageBuilder());
        topic.setUpdateDate(Calendar.getInstance());
        topicDAO.update(topic);

        NotificationContext ctx = NotificationContextImpl.cloneInstance().append(CSPrivatePostPlugin.TICKET, topic).append(CSPrivatePostPlugin.POST, post.getMessage()).append(CSPrivatePostPlugin.POSTER, post.getOwner());
        ctx.getNotificationExecutor().with(ctx.makeCommand(PluginKey.key(CSPrivatePostPlugin.ID))).execute(ctx);
      }
    } catch (Exception e) {
      e.printStackTrace();
    }

  }

  @Override
  public void updatePrivatePost(Post post) {

  }     

  @Override
  public void updatePost(Post post) {

  }

  @Override
  public void updatePost(Post post, int type) {

  }

  @Override
  public void removeActivity(String activityId) {

  }

  @Override
  public void removeComment(String activityId, String commentId) {

  }

  @Override
  public void saveCategory(Category category) {

  }

  @Override
  public void saveForum(Forum forum) {

  }
}
