import { handleStartGame, saveDecor, feedFish, cleanAquarium, messageBox } from "./serverContact.js"

var scene = new Phaser.Scene("game");
var allLoaded = false;
var decorLoaded = false;
var allFilesLoaded = false;
var fisharray = [];
var fishobjects = [];
var decorArray = [];
var decorobjects = [];
var saveButton, cleanButton, feedButton;
var aquariumid =document.getElementsByName('aquariumid')[0].content;
var leftToLoad = 0;
var isDragging = false;
var cursors;
var bgFound=false;
var myMessage;
var isOwner=false;

scene.preload = function() {

	myMessage=messageBox(scene);
	this.load.image('sandbackground','https://images.powerpets.com/image/aquarium/images/sandbackground.png');
	this.load.image('sand1','https://images.powerpets.com/image/aquarium/images/bottomsand0001.png');
	this.load.image('sand2','https://images.powerpets.com/image/aquarium/images/bottomsand0002.png');
	this.load.image('savebutton','https://images.powerpets.com/image/aquarium/btn_save.png');
	this.load.image('feedbutton','https://images.powerpets.com/image/aquarium/images/btn_feed.png');
	this.load.image('cleanbutton','https://images.powerpets.com/image/aquarium/images/btn_clean.png');
	//name,xpos,ypos,image,locked, width,height,frames
	
	async function loadAQData() {
		let response = await handleStartGame(scene,aquariumid,myMessage)

	    return response;
	};


	loadAQData().then(data => {
		if (data["owner"]=="1") isOwner=1;
		loadFish(data);
		loadDecor(data);
	});

	function loadDecor(data) {
		let totdecor=data["account"];
		for (let i=0;i<totdecor;i++) {
			// aid, axp, ayp, adp, aimg, locked, awidth, aheight, aframes
			if (typeof(data["aid"+i]) != "undefined") {
				if (data["locked"+i] == "1") {	
					console.log('LOADING BACKGROUND');
					bgFound=true;				
					scene.load.image('background','https://images.powerpets.com/image/aquarium/'+data["aimg"+i]);
				} else {
					addDecor('decor'+data["aid"+i],data["axp"+i],data["ayp"+i],data["aimg"+i],data["locked"+i],data["awidth"+i],data["aheight"+i],data["aframes"+i],data["adp"+i]);
				}
			}
		}
		decorArray.forEach(loadSprites);
		decorLoaded=true;
		return
	}

	function loadFish(data) {
		// time to load my fish 
		let totfish=data["ficount"];
		for (let i=0;i<totfish;i++) {
			addFish(data["ftype"+i]+i,data["fimg"+i],data["fwidth"+i],data["fheight"+i],data["fframes"+i],data["fspeed"+i],data["fhealth"+i],data["ffeed"+i]);
		}
		fisharray.forEach(loadSprites);
		scene.load.on('complete',function allLoadComplete() { allFilesLoaded=true; });
		allLoaded=true
		return
	}


	function addFish(name,image,width,height,frames,speed,health,feed) {
		var newfish = { name: '', url: '', x: 300, y: 200, width: 0, height: 0, frames: 0, targetx: 0, targety: 0, speed: 10, health: 0, feed: 0 };
		if (typeof(name) == "string") {
			newfish.name=name.replace(/\s/g, '');
			newfish.url='https://images.powerpets.com/image/aquarium/sprites/'+image+'?nocache='+ $.now();
			newfish.width=Number(width); newfish.height=Number(height); newfish.frames=Number(frames);
			newfish.speed=Number(speed); newfish.health=Number(health); newfish.feed=feed; 
			fisharray.push(newfish);
		}
	}

	function addDecor(name,xpos,ypos,image,locked, width,height,frames,depth) {
		var newdecor = { name: '', url: '', locked: 0, x: 0, y: 0, width: 0, height: 0, frames: 0, depth: 0 }
		newdecor.name=name;
		newdecor.url='https://images.powerpets.com/image/aquarium/sprites/'+image+'?nocache='+ $.now();
		newdecor.depth=Number(depth); newdecor.locked=Number(locked); newdecor.x=Number(xpos); newdecor.y=Number(ypos); newdecor.width=Number(width); newdecor.height=Number(height); newdecor.frames=Number(frames);
		decorArray.push(newdecor);
	}

	function loadSprites(item,index,arr) {
		scene.load.spritesheet(arr[index].name, arr[index].url, { frameWidth: arr[index].width, frameHeight: arr[index].height, endFrame: arr[index].frames });

	}
};

scene.create = function() {
	var backgroundimage, sandbg, sand1, sand2;
	sandbg=this.add.image(600,465,'sandbackground');
	sandbg.setDepth(2);
	sand1=this.add.image(600,490,'sand1');
	sand1.setDepth(9999);
	sand2=this.add.image(600,480,'sand2');
	sand2.setDepth(3);
	this.cameras.main.setBounds(0,0,1200,500);
	this.physics.world.setBounds(0,0,1200,500);

	function addButtons() {
		saveButton=scene.add.image(600,30,'savebutton').setDepth(10002);
		saveButton.setInteractive().on('pointerdown',function(pointer) {
			console.log('saving decor');
			saveDecor(scene,aquariumid,decorArray,myMessage);
		});

		cleanButton=scene.add.image(40,30,'cleanbutton').setScale(0.7).setDepth(10000);
		cleanButton.setInteractive().on('pointerdown',function(pointer) {
			cleanAquarium(scene,aquariumid,myMessage);
		}).on('pointerover', function(event) { 
			this.setScale(0.8); 
		}).on('pointerout', function(event) { 
			this.setScale(0.7); 
		});

		feedButton=scene.add.image(80,30,'feedbutton').setScale(0.7).setDepth(10001);
		feedButton.setInteractive().on('pointerdown',function(pointer) {
			feedFish(scene,aquariumid,myMessage);
		}).on('pointerover', function(event) {
			this.setScale(0.8);
		}).on('pointerout', function(event) {
			this.setScale(0.7);
		});

	} 

 	function waitForFish() {
 		if (allFilesLoaded) {
			fisharray.forEach(loadFish);
 		} else {
 			setTimeout(waitForFish,500);
 		}
 	}
 	function waitForDecor() {
 		if (allFilesLoaded) {
			if (bgFound) {
				console.log('background found');
				backgroundimage=scene.add.image(315,250,'background');
				backgroundimage.setDepth(1).setScrollFactor(0);
			} else {
				console.log('BACKGROUND NOT FOUND');
			}
			decorArray.forEach(animateDecor);
		 	if (isOwner) addButtons();
 		} else {
 			setTimeout(waitForDecor,1000);
			if (decorLoaded && allLoaded) scene.load.start();
 		}
 	}

 	
 	waitForFish();
 	waitForDecor();

// 	fisharray.forEach(animateFish);

	function loadFish(item,index,arr) {
		var fishobject, target;
		target= new Phaser.Math.Vector2();
		scene.anims.create({
		    key: arr[index].name+'swim',
		    frames: scene.anims.generateFrameNumbers(arr[index].name, { start: 0, end: arr[index].frames-1 }),
		    frameRate: 10,
		    repeat: -1
		});	
//		fishobject.anims.play(arr[index].name+'swim',true);
		
		fishobject = scene.physics.add.sprite(arr[index].x,arr[index].y,arr[index].name).setDepth(1000+index).play(arr[index].name+'swim').setScale(0.9).setInteractive().on('pointerdown', function() {myMessage(arr[index].name+" - Health:"+arr[index].health/10+"% - Last feed:"+arr[index].feed)});

		fishobject.targetx=target.x=Math.floor(Math.random()*1260);
		fishobject.targety=target.y=Math.floor(Math.random()*350)+50;
		fishobject.speed=arr[index].speed*10;
		if (target.x<fishobject.x) fishobject.setFlipX(true);

		scene.physics.moveToObject(fishobject, target, fishobject.speed);
		fishobjects.push(fishobject);
	};


	function animateDecor(item,index,arr) {
		var decorobject;

		if (arr[index].frames==1) {
			decorobject = scene.add.image(arr[index].x,arr[index].y,arr[index].name); 
		} else {
			decorobject = scene.physics.add.sprite(arr[index].x,arr[index].y,arr[index].name);
			decorobject.setDepth(arr[index].y+(arr[index].height/2));
			scene.anims.create({
			    key: arr[index].name+'animate',
			    frames: scene.anims.generateFrameNumbers(arr[index].name, { start: 0, end: arr[index].frames-1 }),
			    frameRate: 10,
			    repeat: -1
			});	
			decorobject.anims.play(arr[index].name+'animate',true);
		}
		decorobject.setDepth(arr[index].depth);
		if (isOwner) {
			decorobject.setInteractive().on('pointerdown', function(pointer, localx, localy, event) {
				if (this.depth>20) this.setDepth(this.depth-20);
			});
			scene.input.setDraggable(decorobject);
		}
		decorobjects.push(decorobject);
	}

    scene.input.on('dragstart', function (pointer, gameObject) {

        gameObject.setTint(0xff0000);

    });
    scene.input.on('drag', function (pointer, gameObject, dragX, dragY) {

        gameObject.x = dragX;
        gameObject.y = dragY;
        gameObject.setDepth (dragY+(gameObject.height/2));


    });
    scene.input.on('dragend', function (pointer, gameObject) {

        gameObject.clearTint();
	    updateArray(gameObject.texture.key, gameObject.x, gameObject.y, gameObject.depth);

    });

	function updateArray(name, xpos,ypos,depth) {
		decorArray.forEach(function (item,index,arr) {
			if (arr[index].name==name) {
				arr[index].x=xpos;
				arr[index].y=ypos;
				arr[index].depth=depth;
			}
		})
	}

	cursors = scene.input.keyboard.createCursorKeys();
	scene.input.keyboard.removeCapture('SPACE');
/*	cursors = scene.input.keyboard.addKeys(Phaser.Input.Keyboard.KeyCodes.LEFT);
	cursors = scene.input.keyboard.addKeys(Phaser.Input.Keyboard.KeyCodes.RIGHT);
*/
};

scene.update = function() {


	fishobjects.forEach(moveSprites);

	if (cursors.right.isDown) this.cameras.main.scrollX += 5; 
	if (cursors.left.isDown) this.cameras.main.scrollX -= 5;

	function moveSprites(item,index,arr) {
		var target,newydiff,newy;

		var distance = Phaser.Math.Distance.Between(arr[index].x,arr[index].y,arr[index].targetx,arr[index].targety);
		target= new Phaser.Math.Vector2();
		if (arr[index].body.speed>0) {
			if (distance<4) {
				arr[index].body.reset(arr[index].targetx,arr[index].targety);
				arr[index].targetx=target.x=Math.floor(Math.random()*1260);
				newydiff=Math.floor(Math.random()*100)-50;
				newy=arr[index].y+newydiff;
				if (newy<20) newy=60;
				if (newy>400) newy=350;
				arr[index].targety=target.y=newy;
				if (target.x<arr[index].x) {
					arr[index].setFlipX(true);
				} else {
					arr[index].setFlipX(false);
				}
				scene.physics.moveToObject(arr[index], target, arr[index].speed);
			}
		}
	};
}

const config = {
	type: Phaser.AUTO,
	width: 630,
	height: 500,
	backgroundColor: "#5ACBFF",
	scene: scene,
    physics: {
        default: 'arcade',
        arcade: {
            debug: false
        }
    },	parent: 'phaser-div'
};

const aquarium = new Phaser.Game(config);

/*
	_root.bubbler.swapDepths(10010);
	_root.bottomSand.swapDepths(10011);
	_root.infobox.swapDepths(10001);
	_root.btn1.swapDepths(10007);
	_root.btn2.swapDepths(10002);
	_root.btn3.swapDepths(10003);
	_root.btn4.swapDepths(10004);
	_root.movclean.swapDepths(10005);
	_root.movfeed.swapDepths(10006);
	_root.water.swapDepths(100);
*/