const canvas = document.getElementById('visibleCanvas');
const ctx = canvas.getContext('2d');
const cW = 668;
const cH = 889;
canvas.width = cW;
canvas.height = cH;
const exportW = 2673;
const exportH = 3556;
const maxStickers = 100;
var loadingImage;
var isLoading = false;
loadingImage = new Image();
var canvasRatio = 1;
loadingImage.src = 'img/loading.png';
loadingImage.onload = drawLoading;
titleImage = new Image();
titleImage.src = 'img/title.png';
helpImage = new Image();
helpImage.src = 'img/help.png';

const exportCanvas = document.getElementById('invisibleCanvas');
const exportCtx = exportCanvas.getContext('2d');
exportCanvas.width = exportW;
exportCanvas.height = exportH;
document.getElementById('stickerMenu').style.display = 'none';
var drawHelp = false;
var layers = [];
var exportLayers = [];
var exportStickers = [];
var exportCounter = 0;

var stickerLayers = [];
var stickerHeld = -1;
var ratioW = 1

var preloading = [];


function drawLoading()
{
	if(renderReady())
	{
		return;
	}
	ctx.drawImage(titleImage, 0, 0, cW, cH, 0, 0, canvas.width, canvas.height);
}

function toggleHelp()
{
	if(preloading.length > 0){
		return;
	}
	drawHelp = !drawHelp;
	render();
}

function updateCanvasDimensions()
{
	if(window.innerWidth >= cW + 30){
		canvas.width = cW;
		canvas.height = cH;
	} else {
		canvasRatio = window.innerWidth / (cW + 30);
		canvas.style.width   = Math.floor(cW * canvasRatio).toString() + 'px';
		canvas.style.height = Math.floor(cH * canvasRatio).toString()+ 'px';
	}
	var canvasLeft = canvas.offsetLeft + canvas.clientLeft;
	ratioW = (window.innerWidth - (canvasLeft*2)) / cW;
    if (ratioW > 0.98){
    	ratioW = 1;
    }
	ratioW = 1/ratioW;
}

function renderReady()
{
	for(i=0; i < layers.length; i++){
		if (!layers[i].complete){
			return false;
		}
	}
	for(i=0; i < stickerLayers.length; i++){
		if (!stickerLayers[i]["image"].complete){
			return false;
		}
	}
	return true;
}

function render()
{
	if(drawHelp){
		ctx.drawImage(helpImage, 0, 0);
		return;
	}
	if (!renderReady())
	{
		return;
	}
	updateCanvasDimensions();
	ctx.clearRect(0, 0, cW, cH);
	for(i=0; i < layers.length; i++){
		ctx.drawImage(layers[i], 0, 0, cW, cH, 0, 0, canvas.width, canvas.height);
	}
	for(i=0; i < stickerLayers.length; i++){
		ctx.drawImage(stickerLayers[i]["image"], stickerLayers[i]["x"], stickerLayers[i]["y"]);	
	}
	if(stickerHeld > -1){
		ctx.strokeStyle = "#FFFFFF";
		ctx.lineWidth = 3;
		ctx.strokeRect(stickerLayers[stickerHeld]["x"], stickerLayers[stickerHeld]["y"], parseInt(stickerLayers[stickerHeld]["image"].width, 10), parseInt(stickerLayers[stickerHeld]["image"].height, 10));
	}
	isLoading = false;
}	

function setOptionButton()
{
	if(isLoading || preloading.length > 0){
		return;
	}
	var index = parseInt(this.getAttribute('data-index'), 10);
	var option = parseInt(this.getAttribute('data-option'), 10);
	var optionSize = gollyOptions[index]['options'].length;

	if (option < optionSize-1){
		option = option + 1;
	}
	else {
		option = 0;
	}

	this.setAttribute('data-option', option.toString(10));
	updateLayer(index, option);
}

function updateLayer(index, option)
{
	isLoading = true;
	updatedLayer = new Image();
	updatedLayer.src = 'img/small/' + gollyOptions[index]['options'][option] + '.png';
	updatedLayer.setAttribute('data-name', gollyOptions[index]['options'][option]);
	updatedLayer.setAttribute('data-index', option.toString(10));
	updatedLayer.onload = render;
	updatedLayer.onerror = imageError;

	layers[index] = updatedLayer;
}

function exportImage()
{
	if (!renderReady() || exportLayers.length != 0 || preloading.length > 0)
	{
		return;
	}
	isLoading = true;
	ctx.drawImage(loadingImage, 0, 0, cW, cH, 0, 0, canvas.width, canvas.height);
	for(i=0; i < layers.length; i++){
		thisImage = new Image();
		thisImage.src = 'img/large/' + layers[i].getAttribute('data-name') + '.png';
		thisImage.onload = renderExport;
		thisImage.onerror = imageError;
		exportLayers.push(thisImage);
	}
	for(i=0;i<stickerLayers.length;i++){
		thisImage = new Image();
		thisImage.src = 'img/large/' + stickerLayers[i]["name"] + '.png';
		thisImage.onload = renderExport;
		thisImage.onerror = imageError;
		exportStickers.push([thisImage, stickerLayers[i]["x"] * 4, stickerLayers[i]["y"] * 4]);
	}

}

function renderExport()
{
	exportCounter = exportCounter + 1;
	if(exportCounter < (exportLayers.length + exportStickers.length)){
		return;
	}
	exportCtx.clearRect(0, 0, exportW, exportH);
	for(i=0; i < exportLayers.length; i++){
		exportCtx.drawImage(exportLayers[i], 0, 0, exportW, exportH, 0, 0, exportW, exportH);
	}
	for(i=0;i<exportStickers.length;i++){
		exportCtx.drawImage(exportStickers[i][0], exportStickers[i][1], exportStickers[i][2]);
	}

	exportLayers = [];
	exportStickers = [];
	exportCounter = 0;
	isLoading = false;
	render();

	document.getElementById('exportPrompt').style.display = 'inline';
}

function showPopupCanvas()
{
	var exportWindow = window.open('');
	exportWindow.document.write('<h1 style=\";color: #FFFFFF;filter: drop-shadow(0 0 3px #000000);z-index: 99999999;position: fixed;\">Right-click image and select \"Save image as...\"</h1><img src="' + exportCanvas.toDataURL('image/png')  + '" alt="Right click and select \"Save image as...\"">');

}

function showExportCanvas()
{
	document.getElementById('exportPrompt').style.display = 'none';
	document.getElementById('invisibleCanvasContainer').style.display = 'inline';
}

function hideExportCanvas()
{
	document.getElementById('invisibleCanvasContainer').style.display  = 'none';
}

function hideExportPrompt()
{
	document.getElementById('exportPrompt').style.display  = 'none';
}

function loadData()
{
	dataArrayString = document.getElementById('dataInput').value;
	var dataObj;
	try	{
		 dataObj= JSON.parse(dataArrayString);
	} catch (error) {
		alert("Parsing error");
		return;
	}
	if(dataObj.length != 2){
		alert("Array length incorrect");
		return;
	}
	if(dataObj[0].length != layers.length){
		alert('Option length incorrect (' + dataObj[0].length + ')');
		return;
	}
	if(dataObj[1].length > maxStickers){
		alert('Too many sticker layers (>' + maxStickers + ')');
		return;
	}
	for(var i=0;i < layers.length; i++){
		var option = dataObj[0][i];
		if(!Number.isInteger(option)){
			alert('Option not an integer (' + option + ')');
			return;
		}
		if(option >= gollyOptions[i]["options"].length || option < 0){
			alert('Option index out of bounds (Maximum: ' + (gollyOptions[i]["options"].length - 1) + ', index: ' + option);
			return;
		}
		var button = document.getElementById('optionButton' + i.toString(10));
		button.setAttribute('data-option', dataObj[0][i].toString(10));
		updateLayer(i, dataObj[0][i]);
	}
	stickerLayers = [];
	for(var i=0; i<dataObj[1].length; i++){
		var sticker = dataObj[1][i];
		if(sticker[0] >= stickerOptions.length || sticker[0] < 0 || !Number.isInteger(sticker[0])){
			alert('Sticker index out of bounds (Maximum: ' + (stickerOptions.length - 1) + ', index: ' + sticker[0]);
			return;
		}else if( !Number.isInteger(sticker[1]) || !Number.isInteger(sticker[2])){
			alert('Invalid coordinates: X: ' + sticker[1] + ', Y: ' + sticker[2]);
			return;
		}
		addSticker(sticker[0], sticker[1], sticker[2]);
	}
	toggleDataMenu();
}

function toggleDataMenu()
{

	if(document.getElementById('dataMenu').style.display == 'inline'){
		document.getElementById('dataMenu').style.display = 'none';
		return;
	}else{
		document.getElementById('dataMenu').style.display = 'inline';
	}
	var dataArray = [[],[]];
	for(var i=0; i < layers.length; i++)
	{
		dataArray[0].push(parseInt(layers[i].getAttribute('data-index'), 10));
	}
	for(var i=0; i < stickerLayers.length; i++)
	{
		dataArray[1].push([stickerLayers[i]["index"], Math.floor(stickerLayers[i]["x"]), Math.floor(stickerLayers[i]["y"])]);
	}
	dataArrayString = JSON.stringify(dataArray);
	
	document.getElementById('dataInput').value = dataArrayString;

}

function toggleStickerMenu()
{
	if (preloading.length > 0) { 
		return;
	}
	if(stickerHeld > -1){
		stickerLayers.splice(stickerHeld, 1);
		stickerHeld = -1;
		render();
		return;
	}
	if (document.getElementById('stickerMenu').style.display == 'none'){
		document.getElementById('stickerMenu').style.display = 'inline';
		document.getElementById('mainContainer').style.display = 'none';
		document.body.setAttribute('style', 'background-image: url("")')
	} else {
		document.getElementById('stickerMenu').style.display = 'none';
		document.getElementById('mainContainer').style.display = 'inline';
		document.body.setAttribute('style', 'background-image: url("img/pattern.png")')
	}
}

function addStickerButton()
{
	var stickerIndex = parseInt(this.getAttribute('data-index'), 10);
	addSticker(stickerIndex);

	toggleStickerMenu();
}

function addSticker(stickerIndex, stickerX=0, stickerY=0)
{
	if (stickerLayers.length >= maxStickers)
	{
		alert('You have too many stickers applied (Maximum is ' + maxStickers.toString(10) + ')');
		return;
	}
	stickerImage = new Image();
	stickerImage.src = 'img/small/' + stickerOptions[stickerIndex] + '.png';
	stickerImage.onload = render;
	stickerImage.onerror = imageError;

	sticker = {"name":stickerOptions[stickerIndex], "image":stickerImage, "x":stickerX, "y":stickerY, "index":stickerIndex};
	stickerLayers.push(sticker);
}

function onCanvasClick(e)
{
	if(!renderReady || preloading.length > 0){
		return
	}
	var canvasLeft = canvas.offsetLeft + canvas.clientLeft;
    var canvasTop = canvas.offsetTop + canvas.clientTop;
	var x = e.pageX - canvasLeft;
	var y = e.pageY - canvasTop;
	//Scrollbar fucks with this, fix later
	
	x = x * ratioW;
	y = y * ratioW;
	if (stickerHeld < 0){
		//Check if any stickers are under the mouse
		for(var i = 0; i < stickerLayers.length; i++) {
			var sW = Math.floor(ratioW * parseInt(stickerLayers[i]["image"].width, 10));
			var sH = Math.floor(ratioW * parseInt(stickerLayers[i]["image"].height, 10));
			if (y > stickerLayers[i]["y"] && y < stickerLayers[i]["y"] + sH  
				&& x > stickerLayers[i]["x"] && x < stickerLayers[i]["x"] + sW) {
				console.log('Picked up sticker');
				stickerHeld = i;
				render();
        	}
        }
	} else {
		//Drop down sticker
		console.log('Dropped sticker');
		stickerLayers[stickerHeld]["x"] = x - Math.floor(ratioW * parseInt(stickerLayers[stickerHeld]["image"].width, 10) / 2);
		stickerLayers[stickerHeld]["y"] = y - Math.floor(ratioW * parseInt(stickerLayers[stickerHeld]["image"].height, 10) / 2);
		stickerHeld = -1;
		render();
	}
}

function nextPreload()
{
	preloading.splice(preloading.indexOf(this), 1);
	if(preloading.size == 0){
		render();
	}
}

function imageError()
{
	var errorNode = document.createElement('p');
	errorNode.appendChild(document.createTextNode('Failed to load resource: ' + this.src))
	document.getElementById('notification').appendChild(errorNode);
	document.getElementById('notification').style.display = 'inline';
}

//Set up option buttons
for(i = 0; i < gollyOptions.length; i++)
{
	optionButtonContainer = document.getElementById('optionContainer');
	thisButton = new Image();
	thisButton.src = 'img/btn/' + gollyOptions[i]['name'] + '.png';
	thisButton.setAttribute('data-index', i.toString(10));
	thisButton.setAttribute('id', 'optionButton' + i.toString(10));
	thisButton.setAttribute('data-option', '0');
	thisButton.setAttribute('class', 'gameButton');
	thisButton.onclick = setOptionButton;
	optionButtonContainer.appendChild(thisButton);

	thisImage = new Image();
	thisImage.src = 'img/small/' + gollyOptions[i]['options'][0] + '.png';
	thisImage.setAttribute('data-name', gollyOptions[i]['options'][0]);
	thisImage.setAttribute('data-index', '0');
	thisImage.onload = render;
	thisImage.onerror = imageError;
	layers.push(thisImage);
}
//Set up sticker buttons
for(i=0; i<stickerOptions.length; i++)
{
	stickerContainer = document.getElementById('stickerButtonContainer');
	thisButton = new Image();
	thisButton.src = 'img/small/' + stickerOptions[i] + '.png';
	thisButton.setAttribute('data-stickername', stickerOptions[i]);
	thisButton.setAttribute('data-index', i.toString(10));
	thisButton.setAttribute('class', 'stickerButton');
	thisButton.onclick = addStickerButton;
	stickerContainer.appendChild(thisButton);
}

updateCanvasDimensions();

for (var i=0; i < gollyOptions.length; i++){
	for (var n=0; n < gollyOptions[i]["options"].length; n++){
		var preload = new Image();
		preload.src = 'img/small/' + gollyOptions[i]["options"][n] + '.png'
		preload.onload = nextPreload;
		preload.onerror = imageError;
		preloading.push(preload);
	}
}

window.addEventListener('load', render);
window.addEventListener('resize', render);
canvas.addEventListener('click', onCanvasClick);