package;

import haxe.xml.Fast;
import openfl.Assets;
import openfl.geom.Rectangle;
import flixel.FlxG;
import flixel.FlxSprite;
import flixel.FlxState;
import flixel.text.FlxText;
import flixel.ui.FlxButton;
import flixel.util.FlxMath;

/**
 * A FlxState which can be used for the game's menu.
 */
class NightState extends FlxState
{
	public var forceScreen:String = null;

	static var screenIds = [ "day1", "day2", "day3", "day4", "day5", "day6", "day7", "day8", "day9", "daya", "dayb", "dayc", "retry", "fail" ];
	static var screenIndex = 0;

	var screenId:String;

	/**
	 * Function that is called up when to state is created to set it up. 
	 */
	override public function create():Void
	{
		super.create();

		this.clear();

		if (forceScreen != null)
		{
			loadScreen(forceScreen);
		}
		else
		{
			loadScreen(Session.cur.screenId);
		}

		Capture.forceRelease();
	}

	function loadScreen(screenId_:String)
	{
		screenId = screenId_;

		var xml = Xml.parse(Assets.getText("assets/data/Screens.xml"));
		var fast = new Fast(xml.firstElement());

		for (screenFast in fast.nodes.screen)
		{
			if (screenFast.att.id != screenId) continue;

			var back = new FlxSprite();
			back.loadGraphic("assets/images/" + screenFast.att.back);
			add(back);

			if (screenFast.has.button)
			{
				// single central button
				var button = new TextButton(new Rectangle(120, 300-6, 270, 37+6), screenFast.att.button, onClickButton);
				add(button);
			}
			else
			{
				// two buttons
				var buttonL = new TextButton(new Rectangle(55, 300-6, 180, 37+6), screenFast.att.buttonl, onClickButtonL);
				add(buttonL);

				var buttonR = new TextButton(new Rectangle(277, 300-6, 180, 37+6), screenFast.att.buttonr, onClickButton);
				add(buttonR);
			}

			if (FlxG.sound.music == null || FlxG.sound.music.getActualVolume() < 1)
				FlxG.sound.playMusic("assets/music/" + screenFast.att.music);
		}
	}

	function onClickButton()
	{
		if (screenId == "fail")
		{
			// go to title
			FlxG.switchState(new TitleState());
		}
		else
		{
			// go to desk
			FlxG.switchState(new DeskState());
		}
	}

	function onClickButtonL()
	{
		// always go back to the title
		FlxG.switchState(new TitleState());
	}

	/**
	 * Function that is called when this state is destroyed - you might want to 
	 * consider setting all objects this state uses to null to help garbage collection.
	 */
	override public function destroy():Void
	{
		super.destroy();
	}

	/**
	 * Function that is called once every frame.
	 */
	override public function update():Void
	{
		super.update();
	}	
}