package ;
import flixel.util.FlxRandom;
import flixel.FlxG;
import flixel.FlxSprite;
import flixel.group.FlxSpriteGroup;
import flixel.text.FlxBitmapTextField;
using StringTools;

class Alert extends FlxSpriteGroup
{
	var feed:Feed;
	var textField:FlxBitmapTextField;
	var elapsedTimeSinceTextSet:Float;
	var flickerTimes = new Array<Float>();
	var backButton:ImageButton;
	var asterisk:FlxSprite;
	var targetText:String;

	public var text(get,set):String;
	public var job(default,set):Job;

	public var selected(get,set):Bool; function get_selected() { return asterisk.visible; } function set_selected(s:Bool) { asterisk.visible = s; return s; }

	public function new(feed_:Feed)
	{
		super();

		feed = feed_;

		backButton = new ImageButton("assets/images/AlertBack.png", onClick);
		add(backButton);

		textField = new FlxBitmapTextField(Global.lcdFont);
		textField.textColor = 0xc7ff85;
		textField.x = 5;
		textField.y = 6;
		textField.text = " ";
		textField.visible = true;
		add(textField);

		asterisk = new FlxSprite();
		asterisk.loadGraphic("assets/images/AlertAsterisk.png");
		asterisk.x = 161;
		asterisk.y = 6;
		add(asterisk);

		elapsedTimeSinceTextSet = 1000;
		selected = false;

//		var flickerTime = 0.0;
//		for (i in 0...5)
//		{
//			flickerTime += FlxRandom.floatRanged(0.02, 0.2);
//			flickerTimes.push(flickerTime);
//		}
	}

	function onClick()
	{
		feed.onAlertClicked(this);
	}

	function set_job(j:Job)
	{
		job = j;
		if (job != null)
			text = job.alertText;
		else
			text = " ";
		return j;
	}

	function get_text() { return textField.text; }

	function set_text(t:String)
	{
		targetText = t;
		if (textField.text.length == t.length) textField.text = " ";
		selected = false;

		if (targetText.length > 1) Main.playSound("Alert.mp3");

		if (targetText.length != 0)
		{
			elapsedTimeSinceTextSet = 0;
			textField.visible = true;
		}
		else
		{
			elapsedTimeSinceTextSet = 1000;
			textField.visible = false;
			targetText = " ";
		}
		return t;
	}

	public override function update()
	{
		super.update();

		if (elapsedTimeSinceTextSet < 1000)
		{
			elapsedTimeSinceTextSet += FlxG.elapsed;
			if (elapsedTimeSinceTextSet > 0.01)
			{
				if (textField.text.length > targetText.length)
				{
					// shorten
					textField.text = textField.text.substr(0, textField.text.length-1);
					elapsedTimeSinceTextSet = 0;
				}
				else if (textField.text.length < targetText.length)
				{
					// lengthen
					textField.text = targetText.substr(0, textField.text.length+1);
					elapsedTimeSinceTextSet = 0;
				}
				else
				{
					// done
					textField.text = targetText;
					elapsedTimeSinceTextSet = 1000;
				}
			}
		}
	}

}
