// Copyright 2019 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     https://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package com.google.sps.servlets;

import com.google.cloud.vision.v1.AnnotateImageRequest;
import com.google.cloud.vision.v1.AnnotateImageResponse;
import com.google.cloud.vision.v1.BatchAnnotateImagesResponse;
import com.google.cloud.vision.v1.EntityAnnotation;
import com.google.cloud.vision.v1.Feature;
import com.google.cloud.vision.v1.Image;
import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.gson.Gson;
import com.google.protobuf.ByteString;
import com.google.sps.data.AnalysisResults;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet with a GET handler that serves the text of the provided image using the Cloud Vision API.
 */
@WebServlet("/receipt-analysis")
public class ReceiptAnalysisServlet extends HttpServlet {
  /** Serves the text of the image at the requested file path. */
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
    String filePath = request.getParameter("file-path");

    // Ignore requests that don't specify a file path
    if (filePath == null) {
      return;
    }

    AnalysisResults results = new AnalysisResults(retrieveText(filePath));

    Gson gson = new Gson();
    response.setContentType("text/html;");
    response.getWriter().println(gson.toJson(results));
  }

  /** Detects and retrieves text in the specified image. */
  private static String retrieveText(String filePath) {
    String description = "";

    try (InputStream fileInputStream = new FileInputStream(filePath)) {
      List<AnnotateImageRequest> requests = new ArrayList<>();

      ByteString imgBytes = ByteString.readFrom(fileInputStream);

      Image img = Image.newBuilder().setContent(imgBytes).build();
      Feature feat = Feature.newBuilder().setType(Feature.Type.TEXT_DETECTION).build();
      AnnotateImageRequest request =
          AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
      requests.add(request);

      try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
        BatchAnnotateImagesResponse batchResponse = client.batchAnnotateImages(requests);
        AnnotateImageResponse response = batchResponse.getResponsesList().get(0);
        EntityAnnotation annotation = response.getTextAnnotationsList().get(0);

        description = annotation.getDescription();
      }
    } catch (IOException e) {
    }

    return description;
  }
}
@@ -1845,16 +1845,41 @@
 -path%22);
+%0A    ByteString imgBytes;
 %0A%0A    //
@@ -1971,24 +1971,66 @@
 urn;%0A    %7D%0A%0A
+    imgBytes = readImageBytes(filePath);%0A%0A
     Analysis
@@ -2080,24 +2080,24 @@
 eveText(
-filePath
+imgBytes
 ));%0A%0A   
@@ -2235,37 +2235,34 @@
 /** 
-Detects and retrieves text in
+Reads the image bytes from
  the
@@ -2272,21 +2272,20 @@
 ecified 
-image
+path
 . */%0A  p
@@ -2298,16 +2298,20 @@
  static 
+Byte
 String r
@@ -2311,26 +2311,28 @@
 tring re
-trieveText
+adImageBytes
 (String 
@@ -2344,38 +2344,53 @@
 ath)
+ throws IOException
  %7B%0A    
+Byte
 String 
-description = %22%22
+imgBytes
 ;%0A%0A 
@@ -2458,24 +2458,248 @@
 ePath)) %7B%0A  
+    imgBytes = ByteString.readFrom(fileInputStream);%0A    %7D%0A%0A    return imgBytes;%0A  %7D%0A%0A  /** Detects and retrieves text in the provided image. */%0A  private static String retrieveText(ByteString imgBytes) throws IOException %7B%0A
     List%3CAnn
@@ -2751,78 +2751,38 @@
 ();%0A
-%0A
     
-  Byte
 String 
-imgBytes = ByteString.readFrom(fileInputStream)
+description = %22%22
 ;%0A%0A
-  
     
@@ -2846,18 +2846,16 @@
 ();%0A    
- 
- 
 Feature 
@@ -2928,26 +2928,24 @@
 uild();%0A    
-  
 AnnotateImag
@@ -2967,26 +2967,24 @@
 t =%0A        
- 
- 
 AnnotateImag
@@ -3042,26 +3042,24 @@
 g).build();%0A
-  
     requests
@@ -3078,18 +3078,16 @@
 );%0A%0A    
-  
 try (Ima
@@ -3142,26 +3142,24 @@
 create()) %7B%0A
-  
       BatchA
@@ -3236,26 +3236,24 @@
 sts);%0A      
-  
 AnnotateImag
@@ -3320,18 +3320,16 @@
 ;%0A      
- 
- 
 EntityAn
@@ -3399,18 +3399,16 @@
 %0A%0A      
-  
 descript
@@ -3446,46 +3446,8 @@
 ();%0A
-      %7D%0A    %7D catch (IOException e) %7B%0A
     

Read image bytes in separate helper method