package org.exoplatform.cs.service.listener;

import java.util.*;


import org.exoplatform.container.PortalContainer;
import org.exoplatform.cs.dao.LogDAO;
import org.exoplatform.cs.dao.TopicDAO;
import org.exoplatform.cs.dto.LogType;
import org.exoplatform.cs.entity.LogEntity;
import org.exoplatform.cs.entity.TopicEntity;
import org.exoplatform.cs.service.CSConstants;
import org.exoplatform.cs.service.util.CSUtils;
import org.exoplatform.cs.service.util.ForumUtils;
import org.exoplatform.forum.service.ForumService;
import org.exoplatform.services.listener.Event;
import org.exoplatform.services.listener.Listener;
import org.exoplatform.services.listener.ListenerService;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.organization.User;
import org.exoplatform.services.resources.ResourceBundleService;
import org.json.JSONArray;
import org.json.JSONObject;

/**
 * Created by IntelliJ IDEA.
 * User: ali
 * Date: 09/01/17
 * Time: 16:59
 */
public class TicketCreatedLogListener extends Listener<TopicEntity, Map<String,String>>{
  private static final Log LOG = ExoLogger.getLogger(TicketCreatedLogListener.class);
  private static final String TICKET_CREATED_MESSAGE_KEY = "cs.ticket.created.message";

  private LogDAO logDAO;
  private ForumService forumService;
  private ResourceBundleService resourceBundleService;

  public TicketCreatedLogListener(LogDAO logDAO, ForumService forumService, ResourceBundleService resourceBundleService) {
    this.logDAO = logDAO;
    this.forumService = forumService;
    this.resourceBundleService = resourceBundleService;
  }

  @Override
  public void onEvent(Event<TopicEntity, Map<String, String>> event) throws Exception {
    TopicEntity ticket = event.getSource();
    String language = ticket.getSpace().getLanguage();
    Map<String,String> data = event.getData();
    String userID = data.get(CSConstants.USERID);
    Calendar now = Calendar.getInstance();
    LogEntity logEntity = new LogEntity(LogType.TICKET_CREATED,userID,now,null,null,ticket,null,null,ticket.getSpace().getGroupId());
    logDAO.create(logEntity);
/*    LogEntity statusLogEntity = new LogEntity(LogType.TICKET_STATUS_CHANGED, userID, now, "", "open", ticket,null,null,ticket.getSpace().getGroupId());
    logDAO.create(statusLogEntity);*/

    String message = resourceBundleService.getResourceBundle("locale.customer-space", new Locale(language)).getString(TICKET_CREATED_MESSAGE_KEY);
    ForumUtils.postMessageToTicket(forumService,ticket,message);
    LOG.info("Ticket {} was created by {}",ticket.getId(),userID);

  }
}
