/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.ocelotds.core.mtc;

import javax.annotation.Priority;
import javax.decorator.Decorator;
import javax.decorator.Delegate;
import javax.enterprise.inject.Any;
import javax.inject.Inject;
import javax.servlet.http.HttpSession;
import org.ocelotds.Constants;
import org.ocelotds.annotations.OcelotLogger;
import org.ocelotds.messaging.MessageFromClient;
import org.ocelotds.messaging.MessageToClient;
import org.ocelotds.objects.Options;
import org.slf4j.Logger;

/**
 *
 * @author hhfrancois
 */
@Decorator
@Priority(0)
public abstract class RSMonitorDecorator implements RSMessageToClientService {

	@Inject
	@OcelotLogger
	private Logger logger;

	@Inject
	@Delegate
	@Any
	RSMessageToClientService messageToClientService;

	/**
	 * determine if request is monitored
	 * @param session
	 * @return 
	 */
	public boolean isMonitored(HttpSession session) {
		boolean monitor  =false;
		if (null != session && session.getAttribute(Constants.Options.OPTIONS)!=null) {
			monitor = ((Options) session.getAttribute(Constants.Options.OPTIONS)).isMonitor();
		}
		return monitor;
	}

	/**
	 * get t0
	 * @param monitor
	 * @return 
	 */
	protected long getT0(boolean monitor) {
		long t0 = 0;
		if (monitor) {
			t0 = System.currentTimeMillis();
		}
		return t0;
	}

	/**
	 * set timing
	 * @param monitor
	 * @param t0
	 * @param mtc 
	 */
	protected void setTiming(boolean monitor, long t0, MessageToClient mtc) {
		if (monitor) {
			long t1 = System.currentTimeMillis();
			mtc.setTime(t1 - t0);
		}
	}

	/**
	 * Decorate method
	 * @param message
	 * @param session
	 * @return 
	 */
	@Override
	public MessageToClient createMessageToClient(MessageFromClient message, HttpSession session) {
		boolean monitor  = isMonitored(session);
		logger.debug("Monitor is enabled : {}", monitor);
		long t0 = getT0(monitor);
		MessageToClient mtc = messageToClientService.createMessageToClient(message, session);
		setTiming(monitor, t0, mtc);
		return mtc;
	}
}

@@ -1013,16 +1013,21 @@
 itored%0D%0A
+%09 *%0D%0A
 %09 * @par
@@ -1041,33 +1041,32 @@
 ion%0D%0A%09 * @return
- 
 %0D%0A%09 */%0D%0A%09public 
@@ -1058,23 +1058,16 @@
 %0A%09 */%0D%0A%09
-public 
 boolean 
@@ -1120,18 +1120,18 @@
 monitor 
- 
 =
+ 
 false;%0D%0A
@@ -1202,18 +1202,20 @@
 OPTIONS)
+ 
 !=
+ 
 null) %7B%0D
@@ -1346,24 +1346,29 @@
 %09 * get t0%0D%0A
+%09 *%0D%0A
 %09 * @param m
@@ -1378,33 +1378,32 @@
 tor%0D%0A%09 * @return
- 
 %0D%0A%09 */%0D%0A%09protect
@@ -1554,16 +1554,21 @@
 timing%0D%0A
+%09 *%0D%0A
 %09 * @par
@@ -1608,17 +1608,16 @@
 aram mtc
- 
 %0D%0A%09 */%0D%0A
@@ -1816,16 +1816,21 @@
 method%0D%0A
+%09 *%0D%0A
 %09 * @par
@@ -1872,17 +1872,16 @@
  @return
- 
 %0D%0A%09 */%0D%0A
@@ -2007,17 +2007,16 @@
 monitor 
- 
 = isMoni

change scope of method