package kz.cafe.client.rest;

import java.io.*;
import java.util.*;
import javax.servlet.http.*;
import javax.ws.rs.*;
import javax.ws.rs.core.*;
import kz.cafe.client.*;
import kz.cafe.client.rest.wrappers.*;
import kz.cafe.constants.*;
import kz.cafe.db.*;
import kz.cafe.db.model.*;
import org.apache.commons.fileupload.*;
import org.apache.commons.fileupload.disk.*;
import org.apache.commons.fileupload.servlet.*;


@Path("/images")
public class FEImages extends FEAbstractService{

//   private static Log log = LogFactory.getLog(FEImages.class);

   private static final String LOG = "[JR IMAGE] ";





   public FEImages(@Context HttpServletRequest hsr){
      super(ServiceRequestModel.buildUpponServlet(hsr), LOG);
   }




   @POST
   @Path("/new/{SID}")
   @Consumes(MediaType.MULTIPART_FORM_DATA)
   @Produces({ MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
   public JRImageResponse post(@PathParam("SID") String SID, @Context HttpServletRequest request){
      
      JRImageResponse response = new JRImageResponse();
      
      try{
         checkSession(SID);
         

         if(ServletFileUpload.isMultipartContent(request)){
            FileItemFactory factory = new DiskFileItemFactory();

            ServletFileUpload upload = new ServletFileUpload(factory);

            @SuppressWarnings("unchecked")
            List<FileItem> items = upload.parseRequest(request);

            if(items.size() == 0) {
               throw new Exception("Нет файла в запросе");
            }
            else{
               FileItem item = items.get(0);
               
               String sFileExtension;
               
               try{
                  sFileExtension = item.getName().split("\\.")[1].trim();
               }
               catch (Exception e1){
                  throw new Error("Имя файла должно содержать расширение");
               }
               
               
               String sFileName = MongoService.getUniqueID(MImage.class)
                                  + "."
                                  + sFileExtension; 

               FileOutputStream fout =
                  new FileOutputStream(new File(ServerConstants.getImageFolder() + sFileName));

               fout.write(item.get());
               
               response.image = sFileName;

               return response;
            }
         }
         else {
            throw new Exception("Not a multipart form.");
         }
      }
      catch (Throwable e){
         return new JRImageResponse(e);
      }
   }
}
