package foundation.schedule;

import java.util.Iterator;

import foundation.data.entity.Entity;
import foundation.json.IJSONProvider;
import foundation.json.IJSONWriter;
import foundation.util.ID;
import foundation.util.MapList;
import foundation.util.Util;

public class ScheduleBatch implements Iterable<ScheduleJob>, IJSONProvider {

	private String id;
	private String title;
	private String timeExpression;
	private int timeExpressionMinute;
	private String remark;
	private boolean active;
	private MapList<String, ScheduleJob> jobs;
	private int triggerTimes;
	private String instanceId;
	
	
	public ScheduleBatch() {
		jobs = new MapList<String, ScheduleJob>();
		triggerTimes = 0;
		instanceId = ID.newValue();
	}
	
	public void load(Entity entity) {
		id = entity.getString("id");
		title = entity.getString("title");
		timeExpression = entity.getString("time_expression");
		remark = entity.getString("remark");
		active = entity.getBoolean("is_active", true);
		
		String startMinutes = timeExpression.split(" ")[1];
		if (Util.isInteger(startMinutes)) {
			timeExpressionMinute = Integer.valueOf(startMinutes);
		}
		else {
			startMinutes = startMinutes.substring(0, startMinutes.indexOf("/"));
			
			if (Util.isInteger(startMinutes)) {
				timeExpressionMinute = Integer.valueOf(startMinutes);
			}
			else {
				timeExpressionMinute = 0;
			}
		}
	}
	
	public void loadOneJob(ScheduleJob job) {
		//1.
		timeExpressionMinute = job.setTimeExpression(timeExpressionMinute, timeExpression);
		
		job.setBatch(this);
		//2.
		jobs.add(job.getId(), job);
	}
	
	public String getId() {
		return id;
	}

	public boolean isActive() {
		return active;
	}
	
	public String getTitle() {
		return title;
	}

	public String getTimeExpression() {
		return timeExpression;
	}

	public String getRemark() {
		return remark;
	}

	public String getInstanceId() {
		return instanceId;
	}
	
	public String getInstanceId(int triggerTime) {
		if (this.triggerTimes < triggerTime) {
			instanceId = ID.newValue();
			this.triggerTimes = triggerTime;
		}
		
		return instanceId;
	}
	
	@Override
	public Iterator<ScheduleJob> iterator() {
		return jobs.iterator();
	}

	public void writeJSON(IJSONWriter writer) {
		writer.beginObject();
		
		writer.write("title", title);
		writer.write("time_expression", timeExpression);
		
		writer.beginArray("jobs");
		for (ScheduleJob job: jobs) {
			job.writeJSON(writer);
		}
		writer.endArray();
		
		writer.endObject();
	}
	
}