package  
{
	import net.flashpunk.FP;	
	import net.flashpunk.graphics.Image;
	import net.flashpunk.Mask;
	import net.flashpunk.masks.Pixelmask;
	import net.flashpunk.World;
	import net.flashpunk.utils.Draw;
	import net.flashpunk.utils.Input;
	import net.flashpunk.utils.Key;

	/**
	 * ...
	 * @author AntoineGuerchais
	 */
	public class TreeWorld extends World
	{
		[Embed(source = '../assets/graphics/bg.jpg')]
		private const Background:Class;
		[Embed(source = '../assets/levels/game_multiply.jpg')]
		private const Foreground:Class;
		
		public var paused:Boolean;
		private var bg:Image;
		private var fg:Image;
		private var gameTime:Number;
		private var init:Boolean;
		private var theTree:Tree;
		private	var light:Light;
		private var year:Year;
		public var nbBranch:int;
		public var maxBranch:int;
		public var atEnd:Boolean;
		public var countLevel:int;
		
		private var soundManager:SoundManager;
		
		
		public function TreeWorld(maxBranch:int =60, n:int=0) 
		{
			init = false;
			theTree = new Tree();
			year = new Year();
			switch(n)
			{
				case 0: light = new Level1(); break;
				case 1: light = new Level2(); break;
				case 2: light = new Level3(); break;
				case 3: light = new Level4(); break;
				default: light = new Level4(); break;
			}
			this.maxBranch = Math.min(maxBranch,100);
			bg = new Image(Background);
			fg = new Image(Foreground);
			fg.blend = "multiply";
			
			paused = false;
			atEnd = false;
			soundManager = new SoundManager();
			//pMask.threshold = ;
			//addMask(pMask);get
			countLevel = n;
		}
		
		override public function update():void
		{
			gameTime += FP.elapsed;
			if (!init)
			{
				add(year);
				add(new Ground);
				add(theTree);
				add(light);
				add(new Clipper());
				init = true;
			}
			
			var branchList:Array = [];
		    getClass(Branch, branchList);
			nbBranch = Math.min(maxBranch,branchList.length);
			if (!(branchList.length > maxBranch))
			{
				var c:int;
				/*for each(var b:Branch in branchList)
				{
					if (b.childs.length == 0) c++;
				}*/
				nbBranch -= c;
			}
			else
			{
				
				if(!atEnd) gameTime = 0;
				atEnd = true;
				theTree.stop();// = false;
				
				//FP.world.removeAll();
				//FP.world = new TreeWorld();
			}
			if (atEnd && gameTime > 5)
			{
				if (light.branchInLight > 0)
				{
					FP.world.removeAll();
					FP.world = new TreeWorld(10 * light.branchInLight, countLevel + 1);
				}
				else
				{
					FP.world.removeAll();
					FP.world = new MainMenu();
				}
			}
			if (Input.pressed(Key.ESCAPE))
			{
				FP.world.removeAll();
					FP.world = new MainMenu();
			}
			super.update();
		}
		
		public function updateMenu(visible:Boolean):void
		{
		}
		
		
		override public function render():void 
		{
			Draw.graphic(bg);
				super.render();
				Draw.graphic(fg);
			//Draw.blend = "Add";
			//light.blend = "overlay";
			//Draw.graphic(light);
				
		}
	}

}