import Phaser from "phaser";
import ReferenceScene from "./scenes/ReferenceScene";
import DungeonScene from "./scenes/DungeonScene";
import InfoScene from "./scenes/InfoScene";
import CreditsScene from "./scenes/CreditsScene";
import Synth from "./synth";

var gametitle = "Fate of the blood mercenary";
window.gametitle = gametitle;

document.title = gametitle;	

window.addEventListener("blur", function() {
	window.paused = true;
	console.log("paused");
	window.synth.pause();
}, false);
window.addEventListener("focus", function() {
	window.paused = false;
	console.log("resumed");
	window.synth.play();
}, false);

window.paused = document.hidden;
if (!window.paused) {
	window.synth.play();
}

const game = new Phaser.Game({
  type: Phaser.WEBGL,
  width: window.innerWidth,
  height: window.innerHeight,
  render: { pixelArt: true },
  physics: { default: "arcade", arcade: { debug: false, gravity: { y: 0 } } },
  scene: [DungeonScene, InfoScene, ReferenceScene, CreditsScene]
});

window.resetGame = function() {
	localStorage.clear();
	localStorage.playerHp = 100;
	localStorage.playerMaxHp = 150;
	localStorage.playerDamage = 5;
	localStorage.playerSpeed = 125;
	localStorage.playerLeak = 1;
	localStorage.playerInventory = "[]";
};

window.saveGame = function() {
	localStorage.playerHp = window.player.hp;
	localStorage.playerMaxHp = window.player.maxhp;
	localStorage.playerDamage = window.player.damage;
	localStorage.playerSpeed = window.player.speed;
	localStorage.playerInventory = JSON.stringify(window.inventory);
	localStorage.playerLeak = window.playerLeak;
	for (var i = 0; i < window.enemy1.length; ++i) {
		var prefix = "" + window.level + "_" + window.enemy1[i].slimeId + "_";
		localStorage[prefix + 'hp'] = window.enemy1[i].hp;
		localStorage[prefix + 'x'] = window.enemy1[i].sprite.x;
		localStorage[prefix + 'y'] = window.enemy1[i].sprite.y;
	}
	localStorage['openDoors' + window.level] = JSON.stringify(window.openDoors);
	localStorage.profState = window.profState;
	localStorage.julinaState = window.julinaState;
};

if (!localStorage.playerLeak) {
	window.resetGame();
}

window.inventory = JSON.parse(localStorage.playerInventory);
window.playerLeak = +localStorage.playerLeak;

setInterval(function() {
	var player = window.player;
	if (player && player.alive && !window.paused) {
		player.sprite.setTint(0xff0000);
		player.hp = player.hp - window.playerLeak;
		clearTimeout(player.timeoutRed);
		player.timeoutRed = setTimeout(function() {
			player.sprite.setTint(0xffffff);
		}, 100);
	}
}, 5000);

function setUpHotReload() {
  // @ts-ignore
  if (module.hot) {
    // @ts-ignore
    module.hot.accept(() => {});
    // @ts-ignore
    module.hot.dispose(() => {
      window.location.reload();
    });
  }
}

setUpHotReload();

window.addEventListener("resize", () => {
  game.resize(window.innerWidth, window.innerHeight);
});
