/**
 * 
 */
package com.trendrr.oss;

import java.util.Date;
import java.util.concurrent.atomic.AtomicLong;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.trendrr.oss.concurrent.Sleep;


/**
 * 
 * Threadsafe counter that keeps counts of the past and current minute, second, ect.
 * 
 * 
 * @author Dustin Norlander
 * @created Mar 22, 2012
 * 
 */
public class TimeframeCounter {

	protected static Log log = LogFactory.getLog(TimeframeCounter.class);
	
	AtomicLong current = new AtomicLong(0);
	AtomicLong previous = new AtomicLong(0l);
	Timeframe timeframe = Timeframe.MINUTES;
	AtomicLong epoch = new AtomicLong(0);
	
	public TimeframeCounter(Timeframe frame) {
		this.timeframe = frame;
	}

	public long inc() {
		return this.inc(1);
	}
	public long inc(long val) {
		long curepoch = timeframe.toTrendrrEpoch(new Date()).longValue();
		long oldepoch = this.epoch.getAndSet(curepoch);
		if (oldepoch != curepoch) {
			previous.set(current.getAndSet(0));
		}
		return current.addAndGet(val);
	}
	
	/**
	 * Gets the current value for this timeframe
	 * @return
	 */
	public long getCurrent() {
		return this.current.get();
	}
	
	/**
	 * gets the most recently completed value.
	 * @return
	 */
	public long getPrevious() {
		return this.previous.get();
	}
	
}

@@ -583,16 +583,64 @@
 ng(0l);%0A
+%09AtomicLong previousEpoch = new AtomicLong(0l);%0A
 %09Timefra
@@ -1050,16 +1050,48 @@
 et(0));%0A
+%09%09%09previousEpoch.set(oldepoch);%0A
 %09%09%7D%0A%09%09re
@@ -1226,134 +1226,389 @@
 %7B%0A%09%09
-return this.current.get();%0A%09%7D%0A%09%0A%09/**%0A%09 * gets the most recently completed value.%0A%09 * @return%0A%09 */%0A%09public long getPrevious() %7B
+if (timeframe.toTrendrrEpoch(new Date()).longValue() != this.epoch.get()) %7B%0A%09%09%09return 0l;%0A%09%09%7D%0A%09%09return this.current.get();%0A%09%7D%0A%09%0A%09/**%0A%09 * gets the most recently completed from one timeframe ago (ie. yesterday, an hour ago, ect).%0A%09 * @return%0A%09 */%0A%09public long getPrevious() %7B%0A%09%09if ((timeframe.toTrendrrEpoch(new Date()).longValue()-1) != this.previousEpoch.get()) %7B%0A%09%09%09return 0l;%0A%09%09%7D
 %0A%09%09r

check that getprevious is always the most recent possible, else return 0