package ;

import flixel.text.FlxBitmapTextField;
import flixel.group.FlxSpriteGroup;
using StringTools;

class Feed extends FlxSpriteGroup
{
	var terminal:Terminal;
	var alerts = new Array<Alert>();
	var overflowJobs = new List<Job>();
	var timerField:FlxBitmapTextField;
	var sessionIndex:Int;

	static var kAlertHeight = 20;

	public var selectedJob(get,never):Job;
	public var time(never,set):Float;

	public function new(sessionIndex_:Int)
	{
		super();

		sessionIndex = sessionIndex_;

		terminal = new Terminal();
		terminal.x = 9;
		terminal.y = 268-40+8;
		add(terminal);

		for (i in 0...11)
		{
			var alert = new Alert(this);
			alert.x = 0;
			alert.y = i * kAlertHeight;
			alerts.push(alert);
			add(alert);
		}

		timerField = new FlxBitmapTextField(Global.lcdFont);
		timerField.x = 71-12;
		timerField.y = 343;
		timerField.textColor = 0xc7ff85;
		timerField.text = " ";
		add(timerField);

		time = 0;
	}

	function set_time(t:Float)
	{
		var min = Math.floor(t / 60);
		var sec = Math.floor(t % 60);
		timerField.text = "SESSION " + Std.string(sessionIndex+1).lpad("0", 2) + "   " + Std.string(min).lpad("0", 2) + ":" + Std.string(sec).lpad("0", 2);
		return t;
	}

	public function onAlertClicked(alert:Alert)
	{
		for (n in alerts)
		{
			n.selected = (n == alert);
		}
		terminal.animateText(alert.job != null ? alert.job.terminalText : " ");
	}

	public function addJob(job:Job)
	{
		var freeAlerts = [ for (a in alerts) if (a.job == null) a ];
		if (freeAlerts.length != 0)
		{
			var i = Std.random(freeAlerts.length);
			freeAlerts[i].job = job;
		}
		else
		{
			// no free alerts found, add it to overflows
			overflowJobs.push(job);
		}
	}

	public function removeJob(job:Job)
	{
		for (n in alerts)
		{
			if (n.job == job)
			{
				if (n.selected)
					terminal.animateText(" ");
				n.job = null;
				// take from overflowJobs
				if (overflowJobs.length != 0) n.job = overflowJobs.pop();
				return;
			}
		}

		// remove from overflowJobs
		overflowJobs.remove(job);
	}

	function get_selectedJob():Job
	{
		for (n in alerts)
		{
			if (n.selected) return n.job;
		}
		return null;
	}
}
