package com.github.onsdigital.babbage.api.endpoint.content;

import com.github.davidcarboni.restolino.framework.Api;
import com.github.onsdigital.babbage.api.error.ErrorHandler;
import com.github.onsdigital.babbage.content.client.ContentClient;
import com.github.onsdigital.babbage.content.client.ContentResponse;
import com.github.onsdigital.babbage.response.BabbageContentBasedBinaryResponse;

import javax.imageio.IIOException;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.core.Context;
import javax.ws.rs.ext.ExceptionMapper;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * Created by bren on 01/07/15.
 * <p/>
 * Serves resource files from content service with no content disposition
 */
@Api
public class Resource {

    @GET
    public void get(@Context HttpServletRequest request, @Context HttpServletResponse response) throws IOException {
        try {
            String uri = request.getParameter("uri");
            String width = request.getParameter("width");

            ContentResponse contentResponse = ContentClient.getInstance().getResource(uri);
            String contentDispositionHeader = "inline; ";
            contentDispositionHeader += contentResponse.getName() == null ? "" : "filename=\"" + contentResponse.getName() + "\"";
            response.setHeader("Content-Disposition", contentDispositionHeader);

            InputStream contentResponseBody = contentResponse.getDataStream();
            BufferedImage image = null;

            if (width != null) {

                try {
                    Integer w = Integer.parseInt(width, 10);

                    if (uri.toLowerCase().endsWith(".png") || uri.toLowerCase().endsWith(".jpg") || uri.toLowerCase().endsWith(".jpeg")) {
                        image = ImageIO.read(contentResponseBody);
                        Integer clampedWidth = Math.max(1, Math.min(image.getWidth(), w));

                        Double w2 = (double)clampedWidth;
                        Double ratio = w2 / (double)image.getWidth();
                        Double h = (double)image.getHeight() * ratio;

                        Image newImage = image.getScaledInstance(clampedWidth, h.intValue(), Image.SCALE_SMOOTH);
                        image = new BufferedImage(newImage.getWidth(null), newImage.getHeight(null), BufferedImage.TYPE_INT_RGB);
                        image.getGraphics().drawImage(newImage, 0, 0, null);
                    }

                } catch (IOException e) {
                    e.printStackTrace();
                }

            }


            if (image != null) {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                ImageIO.write(image, "png", os);
                contentResponseBody = new ByteArrayInputStream(os.toByteArray());
            }

            new BabbageContentBasedBinaryResponse(contentResponse, contentResponseBody, contentResponse.getMimeType()).apply(request, response);
        } catch (Throwable t) {
            ErrorHandler.handle(request, response, t);
        }
    }

}

@@ -1611,16 +1611,22 @@
         
+ try (
  InputSt
@@ -1675,34 +1675,42 @@
 .getDataStream()
-;%0A
+ ) %7B%0A%0A    
             Buff
@@ -1742,24 +1742,28 @@
             
+    
 if (width !=
@@ -1780,38 +1780,46 @@
                 
+    
 try %7B%0A
+    
                 
@@ -1860,24 +1860,28 @@
 idth, 10);%0A%0A
+    
             
@@ -2023,32 +2023,36 @@
                 
+    
 image = ImageIO.
@@ -2078,16 +2078,20 @@
 eBody);%0A
+    
         
@@ -2194,24 +2194,28 @@
             
+    
 Double w2 = 
@@ -2222,16 +2222,17 @@
 (double)
+ 
 clampedW
@@ -2257,24 +2257,28 @@
             
+   
+ 
 Double ratio
@@ -2285,32 +2285,33 @@
  = w2 / (double)
+ 
 image.getWidth()
@@ -2332,24 +2332,28 @@
             
+  
+  
 Double h = (
@@ -2359,16 +2359,17 @@
 (double)
+ 
 image.ge
@@ -2408,24 +2408,28 @@
             
+ 
+   
 Image newIma
@@ -2506,16 +2506,20 @@
 MOOTH);%0A
+    
         
@@ -2660,24 +2660,28 @@
             
+ 
+   
 image.getGra
@@ -2733,32 +2733,36 @@
                 
+    
 %7D%0A%0A             
@@ -2756,32 +2756,36 @@
                 
+ 
+   
 %7D catch (IOExcep
@@ -2790,24 +2790,138 @@
 eption e) %7B%0A
+                        // intentionally swallowing exception so we can return original image if resize fails%0A    
             
@@ -2957,35 +2957,43 @@
                 
+ 
-%7D%0A%0A
+   %7D%0A%0A    
             %7D%0A%0A%0A
@@ -3000,24 +3000,28 @@
             
+ 
+   
 if (image !=
@@ -3025,24 +3025,29 @@
  != null) %7B%0A
+%0A    
             
@@ -3050,16 +3050,21 @@
         
+try (
 ByteArra
@@ -3107,24 +3107,123 @@
 utStream();%0A
+                         InputStream input = new ByteArrayInputStream(os.toByteArray())) %7B%0A        
             
@@ -3279,74 +3279,193 @@
     
+       
-contentResponseBody = new ByteArrayInputStream(os.toByteArray());%0A
+ new BabbageContentBasedBinaryResponse(contentResponse, input, contentResponse.getMimeType()).apply(request, response);%0A                        return;%0A                    %7D%0A    
     
@@ -3467,32 +3467,37 @@
              %7D%0A%0A
+%0A    
             new 
@@ -3617,32 +3617,46 @@
 est, response);%0A
+            %7D%0A
         %7D catch 

Fix PR comments