
var socket = io();
var cssMap, utilMap, domMap;
var ownId;
var visibleMap = [];
var range = 18; //Sichtweite

var tooltiptexts = {
	"treasure-closed": "Kiste!",
	"treasure-open": "Kiste geöffnet!",
	"item_boots_boots1": "Schuhe: Geschwindigkeit an Land +1",
	"item_boots_boots2": "Schuhe: Geschwindigkeit an Land +2",
	"item_boots_boots3": "Schuhe: Geschwindigkeit an Land +3",
	"item_boots_boots4": "Schuhe: Geschwindigkeit an Land +4",
	"item_boots_boots5": "Schuhe: Geschwindigkeit an Land +5",
	"item_tool_axe1": "Axt: Bäume fällen +1",
	"item_tool_axe2": "Axt: Bäume fällen +2",
	"item_tool_axe3": "Axt: Bäume fällen +3",
	"item_tool_axe4": "Axt: Bäume fällen +4",
	"item_tool_axe5": "Axt: Bäume fällen +5",
	"item_head_head1": "Kopf: Rüstung erhöht +200",
	"item_head_head2": "Kopf: Rüstung erhöht +300",
	"item_head_head3": "Kopf: Rüstung erhöht +400",
	"item_head_head4": "Kopf: Rüstung erhöht +500",
	"item_head_head5": "Kopf: Rüstung erhöht +600",
	"item_chest_chest1": "Brust: Rüstung erhöht +200",
	"item_chest_chest2": "Brust: Rüstung erhöht +300",
	"item_chest_chest3": "Brust: Rüstung erhöht +400",
	"item_chest_chest4": "Brust: Rüstung erhöht +500",
	"item_chest_chest5": "Brust: Rüstung erhöht +600",
	"item_legs_legs1": "Beine: Rüstung erhöht +200",
	"item_legs_legs2": "Beine: Rüstung erhöht +300",
	"item_legs_legs3": "Beine: Rüstung erhöht +400",
	"item_legs_legs4": "Beine: Rüstung erhöht +500",
	"item_legs_legs5": "Beine: Rüstung erhöht +600",
	"item_weapon_sword1": "Schwert: Schaden erhöht 200",
	"item_weapon_sword2": "Schwert: Schaden erhöht 300",
	"item_weapon_sword3": "Schwert: Schaden erhöht 400",
	"item_weapon_sword4": "Schwert: Schaden erhöht 500",
	"item_weapon_sword5": "Schwert: Schaden erhöht 600",
	"item_weapon_stick1": "Stock: Schaden +20",
	"item_item_bone0": "Ganz toller Knochen!",
	"item_item_spaten3": "Spaten: Schneller graben",
	"item_consumable_fish1": "Erhöht deine Lebenspunkte um 20",
	"item_consumable_fish2": "Erhöht deine Lebenspunkte um 10",
	"item_item_dimond1": "Verkaufe den Diamand für 10 Siegpunkte! Bewegungsgeschwindigkeit verlangsamt!",
	"item_item_woods1": "Bündel Holz: Schiff verstärken +1"
}

socket.on('connect', function () {
	ownId = socket.io.engine.id;
	console.log("connect!");
	socket.emit("getmap");
});

socket.on('disconnect', function () {
	$(".player").remove();
});

socket.on('getmap', function (conent) {
	cssMap = conent["cssMap"];
	$("#main").append('<div style="position:absolute; top:0px;left:0px; width:' + cssMap.length * 32 + 'px; height:' + cssMap[0].length * 32 + 'px"></div>');
	utilMap = conent["utilMap"];
	var chestCoords = [0, 0];
	for (var w = 0; w < utilMap.length; w++) { //get chest coords
		for (var h = 0; h < utilMap[w].length; h++) {
			if (utilMap[w][h] == "treasure-closed") {
				chestCoords = [w, h];
			}
		}
	}
	console.log(chestCoords);
	//console.log(cssMap);
	domMap = $("#map");

	domMap.empty();

	var allPlayers = conent["allPlayers"];
	console.log(allPlayers);
	for (var id in allPlayers) {
		addNewPlayer(allPlayers[id], id);
	}
});

socket.on('animation', function (timer) {
	timer = timer / 1000;
	var loader = $('<div id="animationDiv" style="width: 17px; height: 4px; position: absolute; background: linear-gradient(to right, green 50%, rgba(255, 0, 0, 0) 50%); background-size: 200% 100%; background-position:right bottom; top: -16px; left: -12px; border: 1px solid black; border-radius: 5px; transition: all ease ' + timer + 's;"></div>');
	$("#" + ownId).append(loader);
	setTimeout(function () {
		$("#animationDiv").addClass("animate");
	}, 100);

});

socket.on('stopAnimation', function (timer) {
	$("#animationDiv").remove();
});

socket.on('objAction', function (obj) {
	console.log(obj);
	var mapX = obj["mapX"] * 32;
	var mapY = obj["mapY"] * 32 + 3;
	$(".overlay" + obj["socketId"]).remove();
	$("#main").append('<div class="overlay' + obj["socketId"] + '" id="" style="background: rgba(206, 0, 104, 0.45); width:32px; height:32px; z-index:2; position:absolute; top:' + mapY + 'px; left:' + mapX + 'px;"></div>');

});

socket.on('stopAction', function (socketId) {
	$(".overlay" + socketId).remove();
});

socket.on('removeUtil', function (obj) {
	console.log(obj);
	$("." + obj["mapY"] + '-' + obj["mapX"] + '.' + obj["name"]).removeClass(obj["name"])
	utilMap[obj["mapY"]][obj["mapX"]] = "";
});

socket.on('replaceUtil', function (obj) {
	console.log(obj);
	$("." + obj["mapY"] + '-' + obj["mapX"] + '.' + obj["name"]).removeClass(obj["name"]).addClass(obj["newName"]);
	utilMap[obj["mapY"]][obj["mapX"]] = obj["newName"];
});

socket.on('hpChange', function (obj) {
	console.log(obj);
	$(".hpBar").css({"width" : obj+"px"});
});

socket.on('newPlayerHp', function (obj) {
	console.log(obj)
	if(obj.socketId == socket.id) {
		$(".hpBar").css({"width" : obj["hp"]+"px"});
	}

	
});


socket.on('dropItem', function (obj) {
	console.log(obj);
	var utilTitle = tooltiptexts[obj["newName"]] ? tooltiptexts[obj["newName"]] : "";
	domMap.append('<img title="' + utilTitle + '" style="top:' + ((obj["mapY"] * 32)) + 'px; left:' + ((obj["mapX"] * 32)) + 'px; z-index:3; position:absolute;" src="./img/plain.png" class="' + obj["mapY"] + '-' + obj["mapX"] + ' spriteItem spriteUtils ' + obj["newName"] + '">');
});

socket.on('addItemToInventar', function (obj) {
	console.log("addItemToInventar", obj);
	let itemArt = obj.split("_")[1];
	$("#slot_" + itemArt).empty();

	$("#slot_" + itemArt).append('<img style="zoom: 1.3; position: relative; left: -2px;" title="' + tooltiptexts[obj] + '" src="./img/plain.png" class="' + obj + '">');
	// var utilTitle = tooltiptexts[obj["newName"]] ? tooltiptexts[obj["newName"]] : "";
	// domMap.append('<img title="' + utilTitle + '" style="top:' + ((obj["mapY"] * 32)) + 'px; left:' + ((obj["mapX"] * 32)) + 'px; z-index:3; position:absolute;" src="./img/plain.png" class="' + obj["mapY"] + '-' + obj["mapX"] + ' spriteItem spriteUtils ' + obj["newName"] + '">');
});

function addNewPlayer(player, id) {
	if ($("#" + id).length == 0) {
		var modeClass = "default_ship";
		var modeImg = "./img/default_ship.png";
		if (player["mode"] == 1) {
			var modeClass = "guy";
			var modeImg = "./img/plain.png";
		}
		$("#main").append('<div class="player" id="' + id + '" style="position:absolute; top:' + player["y"] + 'px; left:' + player["x"] + 'px; width:7px; height:7px; z-index:100;"><img class="' + modeClass + '" src="' + modeImg + '"></div>');
	}
}

var oldmapX = null;
var oldmapY = null;
var picStep = 0;
var cnt = 0;
let g_allPlayers = {};
socket.on('setpos', function (allPlayers) {
	window.requestAnimationFrame(function () {
		g_allPlayers = allPlayers;
		for (var id in allPlayers) {
			var player = allPlayers[id];
			var playerElement = $("#" + id);
			var playerImg = playerElement.find("img");

			for (var i in player["special"]) {
				if (i == "modechange") {
					if (player["mode"] == 0) { //ship
						playerElement.find("img").attr("src", "./img/default_ship.png");
						playerImg.removeClass(function (index, className) {
							return (className.match(/(^|\s)guy\S+/g) || []).join(' ');
						});
						playerElement.find("img").removeClass("guy");
						playerElement.find("img").addClass("default_ship");
					} else { //land

						playerElement.find("img").removeClass("default_ship");
						playerElement.find("img").addClass("guy");
						playerElement.find("img").attr("src", "./img/plain.png");
					}
				}
			}

			if (playerElement.length == 1) {
				var playerX = Math.floor(player["x"]);
				var playerY = Math.floor(player["y"]);
				var oldPosY = Math.floor(parseFloat($("#" + id).css("top").split("px")[0]));
				var oldPosX = Math.floor(parseFloat($("#" + id).css("left").split("px")[0]));
				if (oldPosY != playerY || oldPosX != playerX) {
					if (ownId === id) {
						window.scrollTo(playerElement.offset().left - $(window).width() / 2, playerElement.offset().top - $(window).height() / 2 + 100);
						var mapX = Math.floor(playerX / 32);
						var mapY = Math.floor(playerY / 32);

						if (oldmapX != mapX || oldmapY != mapY) {
							oldmapX = mapX;
							oldmapY = mapY;

							for (var x = mapX - range; x < mapX + range; x++) {
								if (x >= 0 && x < cssMap.length) {
									for (var y = mapY - range; y < mapY + range; y++) {
										if (y >= 0 && y < cssMap[0].length) {
											if (!visibleMap[x] || !visibleMap[x][y]) {
												var dist = getCoordDist(x, y, mapX, mapY);
												if (dist <= range) {
													domMap.append('<img style="top:' + (y * 32) + 'px; left:' + (x * 32) + 'px; z-index:1;" src="./img/plain.png" i="' + y + '-' + x + '" class="' + y + '-' + x + ' sprite ' + cssMap[y][x] + '">');
													var utilTitle = tooltiptexts[utilMap[y][x]] ? tooltiptexts[utilMap[y][x]] : "";
													domMap.append('<img style="top:' + ((y * 32) - 5) + 'px; left:' + (x * 32) + 'px; z-index:2;" src="./img/plain.png" title="' + utilTitle + '" class="' + y + '-' + x + ' spriteUtils ' + utilMap[y][x] + '">');
													if (!visibleMap[x]) {
														visibleMap[x] = [];
													}
													visibleMap[x][y] = true;
												}
											}
										}
									}
								}
							}
							for (var x in visibleMap) {
								for (var y in visibleMap[x]) {
									if (visibleMap[x][y]) {
										var dist = getCoordDist(x, y, mapX, mapY);
										if (dist > range) {
											domMap.find("." + y + '-' + x).remove();
											visibleMap[x][y] = false;
										}
									}
								}
							}
						}
					}
					var top2Btn = 0;
					var left2right = 0;
					if (oldPosY > playerY) {
						top2Btn = -1;
					} else if (oldPosY < playerY) {
						top2Btn = 1;
					}
					if (oldPosX > playerX) {
						left2right = -1;
					} else if (oldPosX < playerX) {
						left2right = 1;
					}
					var angle = 0;
					if (player["mode"] == 0) { //ship
						var angle = Math.atan2(top2Btn, left2right);
					} else { //land
						cnt++;
						if (cnt % 3 == 0)
							picStep++;
						if (picStep >= 3)
							picStep = 0;
						if (!playerImg.hasClass("guy" + top2Btn + "-" + left2right + "-" + picStep)) {
							playerImg.removeClass(function (index, className) {
								return (className.match(/(^|\s)guy\S+/g) || []).join(' ');
							});
							playerImg.addClass("guy" + top2Btn + "-" + left2right + "-" + picStep);
						}

					}
					playerImg.attr("top2Btn", top2Btn)
					playerImg.attr("left2right", left2right)
					playerElement.css({ "top": player["y"], "left": player["x"], "-webkit-transform": "rotate(" + angle + "rad)" });
				}
			}
		}
	});
});

function getCoordDist(x1, y1, x2, y2) {
	return Math.abs(Math.sqrt(Math.pow(y2 - y1, 2) + Math.pow(x2 - x1, 2)));
}

socket.on('newPlayer', function (newPlayer) {
	var player = newPlayer["player"];
	var id = newPlayer["id"];
	addNewPlayer(player, id);
});

socket.on('playerDisc', function (id) {
	$("#" + id).remove();
});

socket.on('displayMsg', function (msg) {
	showDisplayMsg(msg);
});

socket.on('showHitAnimation', function (playerId) {
	showHitAnimation(playerId);
});

function showDisplayMsg(msg) {
	$(".msgDiv").remove();

	let msgDiv = $('<div class="msgDiv" style="display: table; position:fixed; bottom:10px; left:40%; width:300px; height:20px; background: #80808082; border-radius:5px; border:3px solid #000000d9; padding:15px; text-align: center; font-weight: bold; font-family: monospace; font-size: 1.3em;">' + msg + '</div>');
	$("body").append(msgDiv);
	setTimeout(function () {
		msgDiv.remove();
	}, 3000);
}

function showHitAnimation(playerId) {
	let player = g_allPlayers[playerId];
	if (player) {
		let picWidth = 30;
		let y = player["y"];
		let x = player["x"] - picWidth;

		var playerElement = $("#" + playerId);
		var playerImg = playerElement.find("img");
		let top2Btn = playerImg.attr("top2Btn");
		let left2right = playerImg.attr("left2right");
		var angle = Math.atan2(top2Btn, left2right);

		console.log(top2Btn, left2right)
		// $(".hitbox").remove();
		// $("#main").append('<div class="hitbox" style="z-index: 10; height: '+picWidth*2+'px; width:'+picWidth*2+'px; position:absolute; top:'+(y-picWidth)+'px; left:'+(x)+'px; border-radius:50%; border: 1px solid black;"></div>')
		let hitImg = $('<img  style="z-index: 101; position:absolute; border-spacing: ' + (angle + Math.PI / 2+0.5) + 'px; top: ' + y + 'px; left: ' + x + 'px; opacity: 40%; width:' + picWidth + 'px; transform: rotate(' + (angle + Math.PI / 2+0.5) + 'rad); transform-origin: top right;" src="/img/hit.png">');
		$("#main").append(hitImg);
		hitImg.animate({ borderSpacing: (angle + Math.PI / 2 + Math.PI) }, {
			step: function (now, fx) {
				$(this).css('transform', 'rotate(' + now + 'rad)');
			},
			duration: 150,
			complete : function () {
				hitImg.hide();
			}
		}, 'swing');
	}
}

let defaultSlots = {
	slot_head: $('<img title="Platz für Kopfteile" src="./img/plain.png" class="slot_head">'),
	slot_chest: $('<img title="Platz für Brustteile" src="./img/plain.png" class="slot_chest">'),
	slot_legs: $('<img title="Platz für Beinteile" src="./img/plain.png" class="slot_legs">'),
	slot_boots: $('<img title="Platz für Schuhe" src="./img/plain.png" class="slot_boots">'),
	slot_weapon: $('<img title="Platz für Waffen" src="./img/plain.png" class="slot_weapon">'),
	slot_tool: $('<img title="Platz für Werkzeuge" src="./img/plain.png" class="slot_tool">'),
	slot_item: $('<img title="Platz für Gegenstände" src="./img/plain.png" class="slot_item">'),
}

$(document).ready(function () {
	var viewportmeta = document.querySelector('meta[name="viewport"]');
	viewportmeta.content = 'user-scalable=NO, width=device-width, initial-scale=1.0';
	window.scrollTo(0, 0);
	var keys = {};

	for (var i in defaultSlots) {
		$("#" + i).append(defaultSlots[i]);
	}

	$(document).keydown(function (event) {
		var key = event.which;
		//console.log(key);
		if (key == 37 || key == 38 || key == 39 || key == 40 || key == 71)
			event.preventDefault();
		if (!keys[key]) {

			if (key == 69) {
				socket.emit("actionKey", key);
			} else {
				socket.emit("keyDown", key);
			}
			keys[key] = true;
			return;
		}
		//console.log(event.which)
		if (event.ctrlKey == true && (event.which == '61' || event.which == '107' || event.which == '173' || event.which == '109' || event.which == '187' || event.which == '189')) {
			event.preventDefault();
		}
		
	});

	$(document).keyup(function (event) {
		var key = event.which;
		socket.emit("keyUp", key);
		if (key == 69 || key == 71) {
			$("#animationDiv").remove();
		}
		keys[key] = false;
	});

	$(window).bind('mousewheel DOMMouseScroll', function (event) {
		if (event.ctrlKey == true) {
			event.preventDefault();
		}
	});


});