package org.exoplatform.cs.portlet.ticket;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import javax.inject.Inject;

import juzu.HttpMethod;
import juzu.MimeType;
import juzu.Path;
import juzu.Resource;
import juzu.Response;
import juzu.SessionScoped;
import juzu.View;
import juzu.plugin.jackson.Jackson;
import juzu.template.Template;

import org.apache.commons.fileupload.FileItem;

import org.exoplatform.commons.juzu.ajax.Ajax;
import org.exoplatform.cs.dto.EnvironmentDTO;
import org.exoplatform.cs.dto.IssueSeverity;
import org.exoplatform.cs.dto.IssueType;
import org.exoplatform.cs.dto.TicketDTO;
import org.exoplatform.cs.portlet.common.CSControllerBase;
import org.exoplatform.cs.service.EnvironmentService;
import org.exoplatform.cs.service.TicketService;
import org.exoplatform.forum.service.ForumService;
import org.exoplatform.services.log.ExoLogger;
import org.exoplatform.services.log.Log;
import org.exoplatform.services.organization.OrganizationService;
import org.exoplatform.services.organization.User;
import org.exoplatform.task.service.TaskService;

@SessionScoped
public class TicketController extends CSControllerBase {
  private static Log  LOG          = ExoLogger.getLogger(TicketController.class);

  @Inject
  OrganizationService organizationService;

  @Inject
  EnvironmentService  environmentService;

  @Inject
  TicketService       ticketService;

  @Inject
  TaskService         taskService;

  @Inject
  ForumService        forumService;

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

  List<FileItem>      uploadedFile = new ArrayList<FileItem>();

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

  @Ajax
  @Resource(method = HttpMethod.POST)
  public Response saveTicket(@Jackson TicketDTO ticketDTO) {
    ticketDTO.setSpaceGroupId(getCurrentSpaceId());
    ticketDTO.setFiles(uploadedFile);
    if(IssueType.INFORMATION.equals(ticketDTO.getType())){
      ticketDTO.setSeverity(IssueSeverity.SEVERITY_4);
    }
    try {
      User user = getCurrentUser();
      ticketService.createTicket(ticketDTO, user);
      uploadedFile.clear();
      return ticketDTO.getLink() == null ? Response.ok("OK") : Response.ok(ticketDTO.getLink());
    } catch (Exception e) {
      LOG.error("Error when saving Task/Forum Topic", e);
      return Response.status(500);
    }
  }

  @Ajax
  @juzu.Resource
  public Response.Content prepareImportFile(FileItem file1, FileItem file2, FileItem file3) throws IOException {
    try {
      List<FileItem> fileItems = Arrays.asList(new FileItem[] { file1, file2, file3 });
      for (FileItem fileItem : fileItems) {
        if (fileItem == null) {
          continue;
        }
        if (fileItem.getSize() == 0) {
          return Response.content(500, getResourceBundle().getString("cs.emptyFile"));
        }
        uploadedFile.add(fileItem);
        LOG.info("File imported '{}' with size {} ", fileItem.getName(), fileItem.getSize());
      }
      return Response.ok().content("OK");
    } catch (Throwable e) {
      LOG.error(e);
      return Response.content(500, getResourceBundle().getString("cs.error"));
    }
  }

  @Ajax
  @juzu.Resource
  @MimeType.JSON
  @Jackson
  public List<EnvironmentDTO> getEnvironments() {
    try {
      String spaceGroupId = getCurrentSpaceId();
      List<EnvironmentDTO> environments = environmentService.getSpaceEnvironments(spaceGroupId);
      return environments;
    } catch (Throwable e) {
      LOG.error(e);
      return null;
    }
  }

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

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

}
