package org.exoplatform.cs.portlet.ticketMenu;

import juzu.*;
import juzu.plugin.jackson.Jackson;
import juzu.template.Template;
import org.exoplatform.commons.juzu.ajax.Ajax;
import org.exoplatform.cs.dto.SpaceDTO;
import org.exoplatform.cs.dto.TicketDTO;
import org.exoplatform.cs.portlet.common.CSControllerBase;
import org.exoplatform.cs.service.CSSpaceService;
import org.exoplatform.cs.service.TicketService;
import org.exoplatform.cs.service.tickets.Flow;
import org.exoplatform.cs.service.tickets.FlowState;
import org.exoplatform.cs.service.tickets.TicketStatusFlowService;
import org.exoplatform.cs.service.util.CSUtils;
import org.exoplatform.forum.service.ForumService;
import org.exoplatform.portal.application.PortalRequestContext;
import org.exoplatform.portal.mop.SiteType;
import org.exoplatform.portal.webui.util.Util;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.social.core.identity.model.Identity;
import org.exoplatform.social.core.identity.model.Profile;
import org.exoplatform.social.core.identity.provider.OrganizationIdentityProvider;
import org.exoplatform.social.core.manager.IdentityManager;
import org.json.JSONArray;
import org.json.JSONObject;

import javax.inject.Inject;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;


public class TicketMenuController extends CSControllerBase {

  private static Log  LOG = ExoLogger.getLogger(TicketMenuController.class);
  private String     bundleString;
  ResourceBundle     bundle;
  private List<String> statusList = new ArrayList<String>();


    @Inject
  TicketService ticketService;


  @Inject
  TicketStatusFlowService ticketStatusFlowService;

  @Inject
  CSSpaceService spaceService;

    @Inject
    ForumService forumService;

    @Inject
    IdentityManager identityManager;


    @Inject
    @Path("index.gtmpl")
    Template            indexTmpl;

    @View
    public Response.Content index() {
        return indexTmpl.ok();
    }




    @Ajax
    @Resource
    @MimeType.JSON
    @Jackson
    public Response getBundle(String locale) {
        return super.getBundle(new Locale(locale));
    }



  /**
   * this method returns the static list of ticket types
   *
   * @return
   */
  @Ajax
  @Resource(method = HttpMethod.GET )
  @MimeType.JSON
  @Jackson
  public List<FlowState> getFlowStats(String name) {
    try {
      return ticketStatusFlowService.getFlowbyName(name).getStates();
    } catch (Exception e) {
      LOG.info("Flow  unfound");
    }
    return new ArrayList<FlowState>() ;
  }


  /**
   * this method returns the static list of ticket types
   *
   * @return
   */
  @Ajax
  @Resource(method = HttpMethod.GET )
  @MimeType.JSON
  @Jackson
  public List<String> getAllowedStates (String name) {
    try {
      String role = "customer";
      if(CSUtils.canManage()){
        role="support";
      }
      List<String> roles = new ArrayList<>();
      for (FlowState state : ticketStatusFlowService.getFlowbyName(name).getStates()){
        if(state.getRole().equals("any")||state.getRole().equals(role))
        roles.add(state.getState());
      }
      return roles;
    } catch (Exception e) {
      LOG.info("Flow  unfound");
    }
    return new ArrayList<>() ;
  }



  /**
     * this method returns the current ticket
     *
     * @return
     */
    @Ajax
    @Resource(method = HttpMethod.GET )
    @MimeType.JSON
    @Jackson
    public TicketDTO getTicket() {
        PortalRequestContext requestContext = Util.getPortalRequestContext();
        String uri=  requestContext.getRequest().getRequestURI();
        if(!uri.contains("/forum/topic/")) return null;
        String topicId =uri.split("/forum/topic/")[1].split("/")[0];
        TicketDTO ticketDTO =ticketService.findById(topicId);
        if (ticketDTO.getAssignee()!=null){
            Identity assigneeId = identityManager.getOrCreateIdentity(OrganizationIdentityProvider.NAME, ticketDTO.getAssignee(), false);
            if(assigneeId!=null){
                Profile profile = assigneeId.getProfile();
                ticketDTO.setAssignee(profile.getFullName());
            }
        }
        return  ticketDTO;
    }


  @Ajax
  @Resource(method = HttpMethod.POST)
  @MimeType.JSON
  @Jackson
  public TicketDTO saveTicket(@Jackson TicketDTO ticketDTO) throws Exception {
    try {
      return ticketService.updateTicket(ticketDTO, getCurrentUser());
    } catch (Exception e) {
      LOG.error("Error when updating ticket", e);
      throw e;
    }
  }

    /**
   * this method returns the list of customer spaces
   *
   * @return
   */
  @Ajax
  @Resource(method = HttpMethod.GET )
  @MimeType.JSON
  @Jackson
  public List<SpaceDTO> getSpaces() {
    return spaceService.getAllSpaces();
  }



    @Override
    public Log getLogger() {
        return LOG;
    }


}
