package com.google.launchpod.servlets;

import java.io.IOException;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.repackaged.com.google.gson.Gson;
import com.google.launchpod.data.RSS;
import com.google.launchpod.data.UserFeed;

@WebServlet("/rss-feed")
public class FormHandlerServlet extends HttpServlet {

  private static final long serialVersionUID = 1L;

  public static final String USER_FEED = "UserFeed";
  public static final String PODCAST_TITLE = "title";
  public static final String EMAIL = "email";
  public static final String TIMESTAMP = "timestamp";
  public static final String MP3LINK = "mp3Link";
  public static final String XML_STRING = "xmlString";
  public static final String PUB_DATE= "pubDate";

  private static final String ID = "id";

  public static final Gson GSON = new Gson();

  /**
   * request user inputs in form fields then create Entity and place in datastore
   */
  @Override
  public void doPost(HttpServletRequest req, HttpServletResponse res) throws IOException {
    String podcastTitle = req.getParameter(PODCAST_TITLE);
    String mp3Link = req.getParameter(MP3LINK);
    if((podcastTitle.isEmpty() || podcastTitle == null) || (mp3Link.isEmpty() || mp3Link == null)){
      throw new IOException("No Title or MP3 link inputted, please try again.");
    }

    //Create entity with all desired attributes
    Entity userFeedEntity = new Entity(USER_FEED);
    userFeedEntity.setProperty(PODCAST_TITLE, podcastTitle);
    userFeedEntity.setProperty(MP3LINK, mp3Link);

    // Generate xml string
    String xmlString = "";
    try{
      xmlString = xmlString(userFeedEntity);
      userFeedEntity.setProperty(XML_STRING ,xmlString);
    }catch(IOException e){
      throw new IOException("Unable to create XML string.");
    }

    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    datastore.put(userFeedEntity);

    //return accessible link to user 
    String urlID = KeyFactory.keyToString(userFeedEntity.getKey());
    String rssLink = "https://launchpod-step18-2020.appspot.com/rss-feed?id=" + urlID;
    res.setContentType("text/html");
    res.getWriter().println("<a href=\"" + rssLink + "\">" + rssLink + "</a>");
  }

  /**
  * Display RSS feed xml string that user tries recalling  with the given ID
  */
  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
    // Get ID passed in request
    String id = req.getParameter(ID);
    Key urlID = KeyFactory.stringToKey(id);
    // Search key in datastore
    DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
    // create entity that contains id from datastore
    try {
      Entity desiredFeedEntity = datastore.get(urlID);
      
      //Create user feed object to access rss feed attributes then create RSS feed
      UserFeed desiredUserFeed = UserFeed.fromEntity(desiredFeedEntity);
      RSS rssFeed = new RSS(desiredUserFeed.getTitle(), desiredUserFeed.getLink(), desiredUserFeed.getPubDate());

      // generate xml string
      XmlMapper xmlMapper = new XmlMapper();
      String xmlString = xmlMapper.writeValueAsString(rssFeed);
      res.setContentType("text/xml");
      res.getWriter().println(xmlString);

    //If there is no entity that matches the key
    } catch (EntityNotFoundException e) {
      e.printStackTrace();
      res.setContentType("text/html");
      res.getWriter().println("<p>Sorry. This is not a valid link.</p>");
      return;
    }
  }

  /**
   * Create RSS XML string from given fields
   * 
   * @return xml String
   * @throws IOException
   * @throws Exception
   */
  private static String xmlString(Entity userFeedEntity) throws IOException {
    XmlMapper xmlMapper = new XmlMapper();
    String xmlString = xmlMapper.writeValueAsString(UserFeed.fromEntity(userFeedEntity));
    return xmlString;
  }
}

@@ -1364,16 +1364,162 @@
  Gson();
+%0A  // public static boolean bucketCreated = false;%0A  // TO-DO: check in doPost if bucketCreated == true, if so upload object, if not create bucket
 %0A%0A  /**%0A
@@ -2902,24 +2902,975 @@
 /a%3E%22);%0A  %7D%0A%0A
+  /**%0A   * Uploads an object to Cloud Storage.%0A   * @throws IOException%0A   */%0A  public static void uploadObject(%0A      String projectId, String bucketName, String objectName, String filePath) throws IOException %7B%0A    // The ID of your GCP project%0A    // String projectId = %22launchpod-step18-2020%22;%0A%0A    // The ID of your GCS bucket%0A    // String bucketName = %22launchpod-mp3-files%22;%0A%0A    // The ID of your GCS object%0A    // String objectName = %22your-object-name%22;%0A%0A    // The path to your file to upload%0A    // String filePath = %22path/to/your/file%22%0A%0A    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();%0A    BlobId blobId = BlobId.of(bucketName, objectName);%0A    BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();%0A    storage.create(blobInfo, Files.readAllBytes(Paths.get(filePath)));%0A%0A    System.out.println(%0A        %22File %22 + filePath + %22 uploaded to bucket %22 + bucketName + %22 as %22 + objectName);%0A  %7D%0A%0A
   /**%0A  * Di

add upload object function