package org.exoplatform.cs.service.listener;

import java.util.Calendar;
import java.util.Locale;
import java.util.Map;


import org.exoplatform.container.PortalContainer;
import org.exoplatform.cs.dao.LogDAO;
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.ForumUtils;
import org.exoplatform.forum.service.ForumService;
import org.exoplatform.services.listener.Event;
import org.exoplatform.services.listener.Listener;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.resources.ResourceBundleService;

/**
 * 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);
    logDAO.create(logEntity);
    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);
  }
}
