package controllers;

import org.joda.time.DateTime;

import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;

import models.openfire.Room;
import play.libs.Json;
import play.mvc.Result;

public class RoomStatistics extends Application {

	public static Result jsonShow(Long id, Integer days) {
		Room room = Room.Finder.byId(id);
		if (room == null) {
			return notFound("room with id " + id + " not found!");
		}
		ObjectNode result = Json.newObject();
		result.put("entries", collectEntries(room, days, result.arrayNode()));
		return ok(result);
	}

	private static ArrayNode collectEntries(Room room, Integer days, ArrayNode roomsJson) {
		DateTime from, to;
		to = DateTime.now();
		from = DateTime.now().minusDays(7);
		for (int i = days; i >= 0; i--) {
			to = DateTime.now().minusDays(i);
			from = DateTime.now().minusDays(i + 1);
			roomsJson.add(room.getEntriesFromTo(from.getMillis(), to.getMillis()).size());
		}
		return roomsJson;
	}
}

@@ -186,16 +186,41 @@
 e.Room;%0A
+import play.cache.Cache;%0A
 import p
@@ -234,16 +234,16 @@
 s.Json;%0A
-
 import p
@@ -310,16 +310,75 @@
 tion %7B%0A%0A
+%09private final static int CACHE_TTL_IN_MINUTES = 60 * 10;%0A%0A
 %09public 
@@ -545,16 +545,55 @@
 %22);%0A%09%09%7D%0A
+%09%09String cacheKey = %22roomStats-%22 + id;%0A
 %09%09Object
@@ -630,76 +630,237 @@
 ;%0A%09%09
-result.put(%22entries%22, collectEntries(room, days, result.arrayNode())
+ArrayNode results = (ArrayNode) Cache.get(cacheKey);%0A%09%09if (results == null) %7B%0A%09%09%09results = collectEntries(room, days, result.arrayNode());%0A%09%09%09Cache.set(cacheKey, results, CACHE_TTL_IN_MINUTES);%0A%09%09%7D%0A%09%09result.put(%22entries%22, results
 );%0A%09

add 10 mins Cache for Statistics