package org.exoplatform.cs.portlet.ticket;

import java.io.*;
import java.util.*;

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.io.FileUtils;
import org.exoplatform.commons.file.model.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;
import org.exoplatform.upload.UploadResource;
import org.exoplatform.upload.UploadService;
import org.json.JSONObject;

@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
  UploadService uploadService;

  @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());
    getFiles(ticketDTO.getUploads());
    ticketDTO.setFiles(uploadedFile);
    if(IssueType.INFORMATION.equals(ticketDTO.getType())){
      ticketDTO.setSeverity(IssueSeverity.SEVERITY_4);
    }
    try {
      User user = getCurrentUser();
      ticketService.createTicket(ticketDTO, user, null);
      uploadedFile.clear();
      JSONObject message = new JSONObject();
      message.append("link",ticketDTO.getLink());
      message.append("label",ticketDTO.getTitle());
      return ticketDTO.getLink() == null ? Response.ok("OK") : Response.ok(message.toString());
    } catch (Exception e) {
      LOG.error("Error when saving Task/Forum Topic", e);
      return Response.status(500);
    }
  }

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

  private void getFiles(String[] ids){

    for(String id : ids){
      UploadResource uploadResource = uploadService.getUploadResource(id);
        if (uploadResource != null) {

          try {
            FileItem fileItem = new FileItem(null,id,
                    uploadResource.getMimeType(),
                    "FORUM_ATTACHEMENTS_NAMESPACE",
                    (long)uploadResource.getUploadedSize(),
                    new Date(),
                    getCurrentUser().getUserName(),
                    false,
                    new FileInputStream(uploadResource.getStoreLocation()));
            uploadedFile.add(fileItem);
          } catch (Exception e) {
            e.printStackTrace();
          }

        }


          }
  }

 /* private static void copyInputStreamToFile(InputStream inputStream, File file)
          throws IOException {

    try (FileOutputStream outputStream = new FileOutputStream(file)) {

      int read;
      byte[] bytes = new byte[1024];

      while ((read = inputStream.read(bytes)) != -1) {
        outputStream.write(bytes, 0, read);
      }
    }

  }
*/

}
