package org.exoplatform.cs.portal.handler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.exoplatform.container.PortalContainer;
import org.exoplatform.cs.dto.TicketDTO;
import org.exoplatform.cs.service.TicketService;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.social.core.space.spi.SpaceService;
import org.exoplatform.web.ControllerContext;
import org.exoplatform.web.WebRequestHandler;
import org.exoplatform.web.controller.QualifiedName;

/**
 * Created by eXo Platform SAS.
 * This handler will redirect requests for tickets from /portal/support/Ticket-Nbre to the right URL in the space forum
 * This Handler needs to get added to the controller.xml file by adding this snippet :
 * &lt;!-- Customer space handler --&gt;
 * &lt;route path="/support/{gtn:ticketID}"&gt;
 * &lt;route-param qname="gtn:handler"&gt;
 * &lt;value&gt;customerspace&lt;/value&gt;
 * &lt;/route-param&gt;
 * &lt;/route&gt;
 * 
 * @author Ali Hamdi
 * @since 15/11/17 10:15
 */

public class CustomerSpaceHandler extends WebRequestHandler {

  protected static Log log = ExoLogger.getLogger(CustomerSpaceHandler.class);

  /** . */
  public static final QualifiedName REQUEST_TICKET_ID = QualifiedName.create("gtn", "ticketID");

  @Override
  public String getHandlerName() {
    return "customerspace";
  }

  @Override
  public boolean execute(ControllerContext controllerContext) throws Exception {
    HttpServletRequest req = controllerContext.getRequest();
    HttpServletResponse res = controllerContext.getResponse();
    SpaceService spaceService= (SpaceService) PortalContainer.getComponent(SpaceService.class);
    String requestTicketId = controllerContext.getParameter(REQUEST_TICKET_ID);
    TicketService ticketService = (TicketService) PortalContainer.getComponent(TicketService.class);
    try {
      TicketDTO ticket = ticketService.findByTicketId(requestTicketId);
      String spacePrettyName = spaceService.getSpaceByGroupId(ticket.getSpaceGroupId()).getPrettyName();
      if (ticket != null) {
        String redirectLink = "/portal/g/" + ticket.getSpaceGroupId().replaceAll("/",":") + "/" + spacePrettyName + "/forum/topic/" + ticket.getId();
        log.debug("Redirecting to {}", redirectLink);
        res.sendRedirect(redirectLink);
        return true;
      }
    } catch (Exception e){
      log.error("Exception getting ticket for ticket ID {}",requestTicketId,e);
      return false;
    }

    return false;
  }

  @Override
  protected boolean getRequiresLifeCycle() {
    return true;
  }
}
