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;
  private TopicDAO topicDAO;
  private ListenerService listenerService;
  public TicketCreatedLogListener(LogDAO logDAO, ForumService forumService, ResourceBundleService resourceBundleService, TopicDAO topicDAO, ListenerService listenerService) {
    this.logDAO = logDAO;
    this.forumService = forumService;
    this.resourceBundleService = resourceBundleService;
    this.topicDAO = topicDAO;
    this.listenerService = listenerService;
  }

  @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);

    if(ticket.getAssignee()==null){
        Map<String,Integer> usersMap = new HashMap<>();
      for (User user : CSUtils.getSupportAutoAssignees()){
          usersMap.put(user.getUserName(),0);
      }
      List<Object[]> results = new ArrayList<>();
      results =topicDAO.countUnresolvedTicketsGroupdByAssignee();
      String assignee="";
      int ticketNumber= 5000;
      for (int i = 0; i < results.size(); i++) {
        Object[] arr = results.get(i);
        if((String) arr[0]!=null){
            if(usersMap.containsKey((String) arr[0])){
                usersMap.put((String) arr[0],((Long)arr[1]).intValue());
            }
        }
      }
        for (Map.Entry<String, Integer> entry : usersMap.entrySet())
        {
            if(entry.getValue().intValue()==0){
                assignee=entry.getKey();
                break;
            }
        }
        if (assignee.equals("")){
            for (Map.Entry<String, Integer> entry : usersMap.entrySet())
            {
                if(entry.getValue().intValue()<ticketNumber){
                    assignee=entry.getKey();
                }
            }
        }
      ticket.setAssignee(assignee);
      topicDAO.update(ticket);
        Map<String,String> changes = new HashMap<>();
        changes.put(CSConstants.OLD_ASSIGNEE,null);
        changes.put(CSConstants.NEW_ASSIGNEE,assignee);
        changes.put(CSConstants.USERID, "support");
        listenerService.broadcast(CSConstants.TICKET_UPDATED,ticket,changes);
      LOG.info("Ticket {} has been assigned to {}",ticket.getId(),assignee);
    }
  }
}
