package org.bench4q.agent.plugin.basic.random;

import java.util.ArrayList;
import java.util.List;

import org.bench4q.agent.plugin.ParameterBarn;
import org.bench4q.agent.plugin.Constructor;
import org.bench4q.agent.plugin.Parameter;
import org.bench4q.agent.plugin.Plugin;
import org.bench4q.agent.plugin.behavior.Behavior;
import org.bench4q.agent.plugin.behavior.BehaviorType;
import org.bench4q.agent.utils.ParameterParser;
import org.bench4q.agent.utils.Type.SupportTypes;

@Plugin(value = "Random")
public class Random extends ParameterBarn {
	private String format;
	private int begin = -1;
	private int end = -1;
	private List<String> valueList = new ArrayList<String>();
	private String currentValue;

	@Constructor
	public Random(
			@Parameter(type = SupportTypes.Field, value = "testId") String testId,
			@Parameter(type = SupportTypes.Field, value = "begin") String begin,
			@Parameter(type = SupportTypes.Field, value = "end") String end,
			@Parameter(type = SupportTypes.NField, value = "valueList") String valueList,
			@Parameter(type = SupportTypes.Field, value = "format") String format) {
		super(testId);
		this.format = format;
		this.begin = Integer.parseInt(begin);
		this.end = Integer.parseInt(end);
		this.valueList = ParameterParser.buildNField(valueList);
	}

	@Behavior(value = "next", type = BehaviorType.CONTROL_BEHAVIOR)
	public void next() {
		java.util.Random r = new java.util.Random();
		int result = r.nextInt(this.end - this.begin) + this.begin;
		this.currentValue = String.valueOf(result);
	}

	public String getValue(String var) {
		if (begin == -1 && end == -1) {
			java.util.Random r = new java.util.Random();
			int index = r.nextInt(this.valueList.size());
			this.currentValue = this.valueList.get(index);
		}
		return (this.format == null || this.format.isEmpty()) ? this.currentValue
				: String.format(this.format, this.currentValue);
	}
}
