package foodtruck.server.job;

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.appengine.api.memcache.MemcacheService;
import com.google.inject.Inject;
import com.google.inject.Singleton;

import foodtruck.dao.ApplicationDAO;
import foodtruck.dao.FifteenMinuteRollupDAO;
import foodtruck.model.Application;
import foodtruck.util.Clock;

/**
 * @author aviolette
 * @since 12/9/12
 */
@Singleton
public class PurgeStatsServlet extends HttpServlet {
  private Clock clock;
  private FifteenMinuteRollupDAO dao;
  private MemcacheService memcache;
  private ApplicationDAO appDAO;

  @Inject
  public void PurgeStatsServlet(FifteenMinuteRollupDAO dao, Clock clock, MemcacheService service, ApplicationDAO appDAO) {
    this.dao = dao;
    this.clock = clock;
    this.memcache = service;
    this.appDAO = appDAO;
  }

  @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    dao.deleteBefore(clock.currentDay().minusDays(2));
    // Need to roll these stats up, but for now just cancel
    for (Application application : appDAO.findAll()) {
      memcache.put("service.access.daily."+application.getKey(), 0L);
    }
  }
}

@@ -51,16 +51,81 @@
 ception;
+%0Aimport java.util.logging.Level;%0Aimport java.util.logging.Logger;
 %0A%0Aimport
@@ -451,24 +451,61 @@
 icationDAO;%0A
+import foodtruck.dao.DailyRollupDAO;%0A
 import foodt
@@ -714,16 +714,105 @@
 rvlet %7B%0A
+  private static final Logger log = Logger.getLogger(PurgeStatsServlet.class.getName());%0A
   privat
@@ -932,16 +932,51 @@
  appDAO;
+%0A  private DailyRollupDAO dailyDAO;
 %0A%0A  @Inj
@@ -1098,16 +1098,53 @@
 O appDAO
+,%0A      DailyRollupDAO dailyRollupDAO
 ) %7B%0A    
@@ -1238,16 +1238,52 @@
 appDAO;%0A
+    this.dailyDAO = dailyRollupDAO;%0A
   %7D%0A%0A  @
@@ -1587,21 +1587,21 @@
     
-memcache.put(
+String key = 
 %22ser
@@ -1609,13 +1609,13 @@
 ice.
-acces
+count
 s.da
@@ -1623,9 +1623,11 @@
 ly.%22
-+
+ + 
 appl
@@ -1642,16 +1642,228 @@
 getKey()
+;%0A      try %7B%0A        dailyDAO.updateCount(clock.now().minusHours(1), key, (Long)memcache.get(key));%0A      %7D catch (Exception e) %7B%0A        log.log(Level.WARNING, e.getMessage(), e);%0A      %7D%0A      memcache.put(key
 , 0L);%0A 

Copy memcached stats into persistent daily time series data