package foodtruck.server.dashboard;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.inject.Inject;
import com.google.inject.Singleton;

import org.joda.time.DateTime;
import org.joda.time.LocalDate;
import org.joda.time.format.DateTimeFormatter;

import foodtruck.dao.LocationDAO;
import foodtruck.dao.TruckDAO;
import foodtruck.dao.TruckStopDAO;
import foodtruck.model.Location;
import foodtruck.model.TruckStop;
import foodtruck.server.GuiceHackRequestWrapper;
import foodtruck.util.Clock;
import foodtruck.util.MilitaryTimeOnlyFormatter;

/**
 * @author aviolette
 * @since 1/8/15
 */
@Singleton
public class CompoundEventServlet extends HttpServlet {
  private static final String JSP_PATH = "/WEB-INF/jsp/dashboard/compoundEvent.jsp";
  private final TruckDAO truckDAO;
  private final LocationDAO locationDAO;
  private final DateTimeFormatter timeFormatter;
  private final Clock clock;
  private final TruckStopDAO truckStopDAO;

  @Inject
  public CompoundEventServlet(TruckDAO truckDAO, LocationDAO locationDAO,
      @MilitaryTimeOnlyFormatter DateTimeFormatter formatter, Clock clock, TruckStopDAO truckStopDAO) {
    this.truckDAO = truckDAO;
    this.locationDAO = locationDAO;
    this.timeFormatter = formatter;
    this.clock = clock;
    this.truckStopDAO = truckStopDAO;
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String startTimeParam = req.getParameter("startTime"),
        endTimeParam = req.getParameter("endTime"),
        locationID = req.getRequestURI().substring(req.getRequestURI().lastIndexOf('/') + 1);
    String[] trucks = req.getParameterValues("trucks");
    Location location = locationDAO.findById(Long.valueOf(locationID));
    if (location == null) {
      resp.sendError(404);
      return;
    }
    LocalDate now = clock.currentDay();
    DateTime startTime = now.toDateTime(timeFormatter.parseLocalTime(startTimeParam), clock.zone()),
        endTime = now.toDateTime(timeFormatter.parseLocalTime(endTimeParam), clock.zone());
    for (String truckId : trucks) {
      TruckStop stop = TruckStop.builder()
          .location(location)
          .startTime(startTime)
          .endTime(endTime)
          .truck(truckDAO.findById(truckId))
          .build();
      truckStopDAO.save(stop);
    }
    resp.sendRedirect("/admin/trucks");
  }

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    String locationID = req.getRequestURI().substring(req.getRequestURI().lastIndexOf('/') + 1);
    Location location = locationDAO.findById(Long.valueOf(locationID));
    if (location == null) {
      resp.sendError(404);
      return;
    }
    req.setAttribute("location", location);
    req.setAttribute("trucks", truckDAO.findActiveTrucks());
    req.setAttribute("nav", "location");
    req = new GuiceHackRequestWrapper(req, JSP_PATH);
    req.getRequestDispatcher(JSP_PATH).forward(req, resp);
  }
}

@@ -57,16 +57,81 @@
 ception;
+%0Aimport java.util.logging.Level;%0Aimport java.util.logging.Logger;
 %0A%0Aimport
@@ -318,21 +318,220 @@
 gle.
-inject.Inject
+api.services.calendar.Calendar;%0Aimport com.google.api.services.calendar.model.Event;%0Aimport com.google.api.services.calendar.model.EventDateTime;%0Aimport com.google.inject.Inject;%0Aimport com.google.inject.Provider
 ;%0Aim
@@ -1084,16 +1084,108 @@
 rvlet %7B%0A
+  private static final Logger log = Logger.getLogger(CompoundEventServlet.class.getName());%0A
   privat
@@ -1457,16 +1457,69 @@
 StopDAO;
+%0A  private final Provider%3CCalendar%3E calendarProvider;
 %0A%0A  @Inj
@@ -1696,16 +1696,53 @@
 kStopDAO
+, Provider%3CCalendar%3E calendarProvider
 ) %7B%0A    
@@ -1901,16 +1901,62 @@
 topDAO;%0A
+    this.calendarProvider = calendarProvider;%0A
   %7D%0A%0A  @
@@ -2714,24 +2714,72 @@
 ck.zone());%0A
+    Calendar calendar = calendarProvider.get();%0A
     for (Str
@@ -3031,16 +3031,696 @@
 (stop);%0A
+      try %7B%0A        Event event = new Event();%0A        event.setLocation(location.getName());%0A        event.setSummary(truckId);%0A        EventDateTime dt = new EventDateTime();%0A        dt.setDateTime(new com.google.api.client.util.DateTime(startTime.getMillis()));%0A        event.setStart(dt);%0A        dt = new EventDateTime();%0A        dt.setDateTime(new com.google.api.client.util.DateTime(endTime.getMillis()));%0A        event.setEnd(dt);%0A        Event createdEvent = calendar.events().insert(truckId, event).execute();%0A        log.log(Level.FINE, %22Created event %7B%7D%22, createdEvent.getId());%0A      %7D catch (Exception e) %7B%0A        log.log(Level.WARNING, e.getMessage(), e);%0A      %7D%0A
     %7D%0A  

Handle creation of google calendar events that mirror what's in database