package com.isartdigital.game;
import com.isartdigital.game.sprites.CheckItem;
import com.isartdigital.game.sprites.Player;
import com.isartdigital.game.sprites.Score;
import com.isartdigital.ui.popin.WinPopin;
import com.isartdigital.ui.UIManager;
import com.isartdigital.utils.Config;
import com.isartdigital.utils.game.GameStage;
import com.isartdigital.game.sprites.TimerHUD;
import com.isartdigital.utils.sounds.SoundManager;
import haxe.ds.Vector;
import haxe.Timer;
import com.isartdigital.utils.system.DeviceCapabilities;
import pixi.core.math.Point;
import pixi.core.math.shapes.Rectangle;
import pixi.core.sprites.Sprite;
import pixi.core.textures.Texture;

	
/**
 * ...
 * @author Cindy Asselin de Beauville
 */
class LevelManager 
{
	
	/**
	 * instance unique de la classe LevelManager
	 */
	private static var instance: LevelManager;
	private static inline var TOPICKNUMBER: Int = 3;
	
	private static inline var OBJECTINTERVAL: Int = 5000;			//
	private static inline var OBJECTINTERVALMIN: Int = 4000; 	// OBJECTINTERVALMIN + rand(0 -> OBJECTINTERVAL);
	
	private static inline var DESAPPEARTIMER: Int = 3000; // temps d'existence des bulles
	private static inline var _PNG: String = ".png";
	
	public var clearInterval:Bool = false;
	
	private var objects: Array<String> = [	"vase", // 1
											"symbales", // 2
											"riz", // 3
											"pinceau", // 4
											"percussions", // 5
											"masque", // 6
											"lanterne", // 7
											"homard", // 8
											"grue", // 9
											"eventail", // 10
											"choux", // 11
											"canardlaque", // 12
											"bouteille", // 13
											"lapin", // 14
											"stele"]; // 15
	
	public var toPickObjects:Array<String> 	= new Array<String> ();
	private var otherObjects:Array<String> 		= new Array<String> ();
	public var currentObjects:Array<String> 	= new Array<String> ();
	
	public var time:UInt = 45;
	
	/**
	 * Retourne l'instance unique de la classe, et la crée si elle n'existait pas au préalable
	 * @return instance unique
	 */
	public static function getInstance (): LevelManager {
		if (instance == null) instance = new LevelManager();
		return instance;
	}
	
	/**
	 * constructeur privé pour éviter qu'une instance soit créée directement
	 */
	private function new() 
	{
		// setTime() à placer au commencement du jeu.
	}
	
	public function setTimer() :Void {
		Timer.delay(function() {
			time --;
			TimerHUD.getInstance().setTimer(time);
			if (time != 0 ) setTimer();
			else {
				UIManager.getInstance().openPopin(WinPopin.getInstance());
				clearInterval = true;
			}
		},1000);
	}
	
	public function apparitionTimer() :Void {
		Timer.delay(function() {
		//	SoundManager.getSound("objectSpawn").play();
			currentObjects = pickObjects().copy();
			if (clearInterval) return;
			spawnObjects();
			apparitionTimer();
		},Math.round(Math.random()*OBJECTINTERVAL + OBJECTINTERVALMIN));
	}
	
	public function toBePicked(?pString:String = null): Bool {
		var lIsRight:Bool = (toPickObjects.indexOf(pString) != -1);
		//	SoundManager.getSound(lIsRight ? "rightObject":"wrongObject").play();
		var lScreen:Rectangle = DeviceCapabilities.getScreenRect(GameStage.getInstance());
		var lCheck: CheckItem;
		if ( pString != null ) {
			if (lIsRight) {
				Score.getInstance().actualScore += 500;
				lCheck = new CheckItem(true);
				
				if (Math.random() < 0.5) SoundManager.getSound("Yes").play();
				else SoundManager.getSound("Ouiii").play();
				
			} else {
				lCheck = new CheckItem(false);
				
				if (Math.random() < 0.5) SoundManager.getSound("Nooo").play();
				else SoundManager.getSound("Ooow").play();
				
				if (GameManager.getInstance().currentSound == "MainloopCouche2") {
					SoundManager.getSound(GameManager.getInstance().currentSound).fade(1, 0, 1000);
					GameManager.getInstance().currentSound = "MainloopCouche1";
					SoundManager.getSound(GameManager.getInstance().currentSound).fade(0, 1, 1000);
				}
				else if (GameManager.getInstance().currentSound == "MainloopCouche3") {
					SoundManager.getSound(GameManager.getInstance().currentSound).fade(1, 0, 1000);
					GameManager.getInstance().currentSound = "MainloopCouche2";
					SoundManager.getSound(GameManager.getInstance().currentSound).fade(0, 1, 1000);
				}
				
				if (GameManager.levelLayer > 0) {
					GameManager.levelLayer --;
					return lIsRight;
				}
			}
				
			if (pString == currentObjects[0]) {
				lCheck.position.set(lScreen.x + lScreen.width / 3,
									lScreen.y + lScreen.height / 3);
			} else if (pString == currentObjects[1]) {
				lCheck.position.set(lScreen.x + lScreen.width * 2/3,
									lScreen.y + lScreen.height / 3);
			}
			else {
				lCheck.position.set(lScreen.x + lScreen.width * 0.5,
									lScreen.y + lScreen.height / 4.2);
				lCheck.scale = new Point(0.4, 0.4);
			}
			GameStage.getInstance().addChild(lCheck);
			return lIsRight;
		} else {
			if (GameManager.levelLayer > 0) GameManager.levelLayer --;
		return lIsRight;
			
		}
		
	}
	
	private function spawnObjects():Void {
		//trace(Texture.fromImage("/assets/Inputzone.png"));
		
		var lScreen:Rectangle = DeviceCapabilities.getScreenRect(GameStage.getInstance());
		
		var obj_1:Sprite = new Sprite(Texture.fromImage("/assets/"+currentObjects[0]+".png"));
		var obj_2:Sprite = new Sprite(Texture.fromImage("/assets/"+currentObjects[1]+".png"));
		
		var bulle_1:Sprite = new Sprite(Texture.fromImage("/assets/Bulle_objetgauche.png"));
		var bulle_2:Sprite = new Sprite(Texture.fromImage("/assets/Bulle_objetdroit.png"));
		
		obj_1.anchor.set(0.5, 0.5);
		obj_2.anchor.set(0.5, 0.5);
		
		bulle_1.anchor.set(0.5, 0.5);
		bulle_2.anchor.set(0.5, 0.5);
		
		GameStage.getInstance().addChild(bulle_1);
		GameStage.getInstance().addChild(bulle_2);
		
		GameStage.getInstance().addChild(obj_1);
		GameStage.getInstance().addChild(obj_2);
		
		obj_1.position.set(	lScreen.x + lScreen.width / 3,
							lScreen.y + lScreen.height / 3);
		obj_2.position.set(	lScreen.x + lScreen.width * 2/3,
							lScreen.y + lScreen.height / 3);
		
		bulle_1.position.set(	lScreen.x + lScreen.width / 2.9,
								lScreen.y + lScreen.height / 2.9);
		bulle_2.position.set(	lScreen.x + lScreen.width * 2/2.95,
								lScreen.y + lScreen.height / 2.9);
		
		obj_1.scale = new Point (0.4, 0.4);
		obj_2.scale = new Point (0.4, 0.4);
		
		bulle_1.scale = new Point (0.5,0.5);
		bulle_2.scale = new Point (0.5,0.5);
		
		Timer.delay(function() {
			obj_1.parent.removeChild(obj_1);
			obj_2.parent.removeChild(obj_2);
			obj_1.destroy();
			obj_2.destroy();
			bulle_1.parent.removeChild(bulle_1);
			bulle_2.parent.removeChild(bulle_2);
			bulle_1.destroy();
			bulle_2.destroy();
			if (clearInterval) return;
			toBePicked(lootObject());
		},DESAPPEARTIMER);
	}
	
	public function lootObject():String
	{
		var lootedObject:String;
		if 		(Player.getInstance().leftState) lootedObject = currentObjects[0];
		else if (Player.getInstance().rightState) lootedObject = currentObjects[1];
		else 	lootedObject = "";
		return 	lootedObject;
	}
	
	public function setObjects() :Void {
		var lObjects:Array<String> = objects.copy();
		var currentIndex:Int;
		for (i in 0...TOPICKNUMBER) {
			currentIndex = Math.floor(Math.random() * lObjects.length);
			toPickObjects.push(lObjects[currentIndex]);
			lObjects.splice(currentIndex, 1);
		}
		otherObjects = lObjects.copy();
	}
	
	private function randValue(pArray:Array<String>) : String {
		return pArray[Math.floor(Math.random() * pArray.length)];
	}
	
	public function pickObjects() :Array<String> {
		var lArray : Array<String> = new Array<String>();
		lArray.push(randValue(toPickObjects));
		Math.random() > 0.5 ? lArray.unshift(randValue(otherObjects)) : lArray.push(randValue(otherObjects));
		return lArray;
	}
	/**
	 * détruit l'instance unique et met sa référence interne à null
	 */
	public function destroy (): Void {
		instance = null;
	}

}