// 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.appengine.api.blobstore.BlobInfo;
import com.google.appengine.api.blobstore.BlobInfoFactory;
import com.google.appengine.api.blobstore.BlobKey;
import com.google.appengine.api.blobstore.BlobstoreService;
import com.google.appengine.api.blobstore.BlobstoreServiceFactory;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.EmbeddedEntity;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.GeoPt;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.sps.COMMONS;
import com.google.sps.data.HttpServletUtils;
import com.google.sps.data.Vendor;
import java.io.IOException;
import java.time.LocalTime;
import java.time.format.DateTimeParseException;
import java.util.List;
import java.util.Map;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * When the user submits the form, Blobstore processes the file upload and then forwards the request
 * to this servlet to update a vendor information
 */
@WebServlet("/update-vendor")
public class UpdateVendorServlet extends HttpServlet {

  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {
    UserService userService = UserServiceFactory.getUserService();
    
    if (userService.isUserLoggedIn()) {
      String firstName = HttpServletUtils.getParameter(request, "firstName", "");
      String lastName = HttpServletUtils.getParameter(request, "lastName", "");
      String phoneNumber = HttpServletUtils.getParameter(request, "phoneNumber", "");
      
      // Get values to add/update vendor's profile picture
      String currentBlobKey = HttpServletUtils.getParameter(request, "blobKey", "");
      BlobKey imageBlobKey = getUploadedFileBlobKey(request, "imageFile");
      String altText = HttpServletUtils.getParameter(request, "altText", "");
      // If nothing was uploaded and there is a current picture, keep current
      if (!currentBlobKey.isEmpty() && imageBlobKey == null) {
        imageBlobKey = new BlobKey(currentBlobKey);
      }

      // Check values are not empty or outside range
      if (firstName.isEmpty() || lastName.isEmpty() || phoneNumber.isEmpty() || altText.isEmpty() || 
          imageBlobKey == null) {
        System.out.println("The values do not exist and/or are outside the range.");
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
      }

      DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();

      Key vendorKey = KeyFactory.createKey("Vendor", userService.getCurrentUser().getUserId());
      Entity vendorEntity;
      try {
        vendorEntity = datastore.get(vendorKey);
      } catch (EntityNotFoundException e) {
        System.out.println(e);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
      }
      Vendor vendorObject = new Vendor(vendorEntity);

      Entity picture;
      // If the vendor doesn't have a picture, create completely new entity
      // Else, use the already existing entity
      if (vendorObject.getProfilePic() == null) {
        picture = new Entity("Picture", vendorKey);
      } else {
        picture = new Entity("Picture",
            vendorObject.getProfilePic().getId(), vendorKey);
      }

      // If not the same, delete previous blob from blobstore
      if (vendorObject.getProfilePic() != null && 
          imageBlobKey.compareTo(vendorObject.getProfilePic().getBlobKey()) != 0) {
        BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
        blobstoreService.delete(vendorObject.getProfilePic().getBlobKey());
      }
      picture.setProperty("blobKey", imageBlobKey);
      picture.setProperty("altText", altText);
      datastore.put(picture);

      EmbeddedEntity picInfo = new EmbeddedEntity();
      picInfo.setKey(picture.getKey());
      picInfo.setPropertiesFrom(picture);

      vendorEntity.setProperty("firstName", firstName);
      vendorEntity.setProperty("lastName", lastName);
      vendorEntity.setProperty("phoneNumber", phoneNumber);
      vendorEntity.setProperty("profilePic", picInfo);
      datastore.put(vendorEntity);
      
      response.sendRedirect("/");
    } else {
      System.out.println("User is not logged in.");
      response.sendError(HttpServletResponse.SC_UNAUTHORIZED);
    }
  }

  /** Returns a BlobKey for the uploaded file, or null if the user didn't upload a file. */
  private BlobKey getUploadedFileBlobKey(HttpServletRequest request, String formInput) {
    BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();
    Map<String, List<BlobKey>> blobs = blobstoreService.getUploads(request);
    List<BlobKey> blobKeys = blobs.get(formInput);

    // User submitted form without selecting a file (dev server)
    if (blobKeys == null || blobKeys.isEmpty()) {
      return null;
    }

    // Our form only contains a single file input, so get the first index.
    BlobKey blobKey = blobKeys.get(0);

    // User submitted form without selecting a file (live server)
    BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);
    if (blobInfo == null || blobInfo.getSize() == 0) {
      blobstoreService.delete(blobKey);
      return null;
    }

    // Validate the file is an image file (.png, .jpg, .jpeg, .jfif, .pjpeg, .pjp)
    String blobMimeType = blobInfo.getContentType();
    if (blobMimeType.equals("image/png") || blobMimeType.equals("image/jpeg")) {
      return blobKey;
    } else {
      blobstoreService.delete(blobKey);
      return null;
    }
  }
}

@@ -620,119 +620,8 @@
 s;%0A%0A
-import com.google.appengine.api.blobstore.BlobInfo;%0Aimport com.google.appengine.api.blobstore.BlobInfoFactory;%0A
 impo
@@ -663,24 +663,24 @@
 re.BlobKey;%0A
+
 import com.g
@@ -1100,57 +1100,8 @@
 on;%0A
-import com.google.appengine.api.datastore.GeoPt;%0A
 impo
@@ -1310,39 +1310,8 @@
 ry;%0A
-import com.google.sps.COMMONS;%0A
 impo
@@ -1418,129 +1418,8 @@
 on;%0A
-import java.time.LocalTime;%0Aimport java.time.format.DateTimeParseException;%0Aimport java.util.List;%0Aimport java.util.Map;%0A
 impo
@@ -2488,16 +2488,33 @@
 obKey = 
+HttpServletUtils.
 getUploa
@@ -5052,24 +5052,24 @@
 gged in.%22);%0A
+
       respon
@@ -5132,1238 +5132,7 @@
 %0A  %7D
-%0A%0A  /** Returns a BlobKey for the uploaded file, or null if the user didn't upload a file. */%0A  private BlobKey getUploadedFileBlobKey(HttpServletRequest request, String formInput) %7B%0A    BlobstoreService blobstoreService = BlobstoreServiceFactory.getBlobstoreService();%0A    Map%3CString, List%3CBlobKey%3E%3E blobs = blobstoreService.getUploads(request);%0A    List%3CBlobKey%3E blobKeys = blobs.get(formInput);%0A%0A    // User submitted form without selecting a file (dev server)%0A    if (blobKeys == null %7C%7C blobKeys.isEmpty()) %7B%0A      return null;%0A    %7D%0A%0A    // Our form only contains a single file input, so get the first index.%0A    BlobKey blobKey = blobKeys.get(0);%0A%0A    // User submitted form without selecting a file (live server)%0A    BlobInfo blobInfo = new BlobInfoFactory().loadBlobInfo(blobKey);%0A    if (blobInfo == null %7C%7C blobInfo.getSize() == 0) %7B%0A      blobstoreService.delete(blobKey);%0A      return null;%0A    %7D%0A%0A    // Validate the file is an image file (.png, .jpg, .jpeg, .jfif, .pjpeg, .pjp)%0A    String blobMimeType = blobInfo.getContentType();%0A    if (blobMimeType.equals(%22image/png%22) %7C%7C blobMimeType.equals(%22image/jpeg%22)) %7B%0A      return blobKey;%0A    %7D else %7B%0A      blobstoreService.delete(blobKey);%0A      return null;%0A    %7D%0A  %7D
 %0A%7D%0A

Remove extra imports