var cellHeight;
var cellWidth;
var nikiItems;
var northWallImage = new Image();
var southWallImage = new Image();
var westWallImage = new Image();
var eastWallImage = new Image();
var itemImage = new Image();
const minWidthLeftBox = 675;
const minWidthRightBox = 320;

function loadPage() {
    row = 9;
    //column = 10;
    cellHeight = 50;
    cellWidth = 60;
    currentX = 30;
    currentY = 25;
    actorRow = 0;
    actorColumn = 0;
    actorDirection = "east";
    nikiItems = 0;
    actorImageSrc = "./images/niki_right.png";
    actorImage.src = actorImageSrc;
    actorImage.onload = function () {
        actorMouseEvents();
        drawActor();
    }
    verticalWallImage.src = "./images/verticalWall.png";
    horizontalWallImage.src = "./images/horizontalWall.png"
    northWallImage.src = "./images/northWall.png";
    southWallImage.src = "./images/southWall.png";
    westWallImage.src = "./images/westWall.png";
    eastWallImage.src = "./images/eastWall.png";
    itemImage.src = "./images/item.png";
    canvas = document.getElementById("territoryId");

    var windowWidth = getWindowWidth();
    setAreasWidth(windowWidth, true);
    setTitelWidth(windowWidth);
    setAreasHeight(getWindowHeight(), true);

    console.log("rows: ", row, ", columns: ", column);
    initTerritory();

    if (canvas.getContext) {
        territory = canvas.getContext("2d");
        drawBasicTerritory();
    } else {
        alert("Es werden Safari oder Firefox 1.5+ benötigt.");
    }

    saveTemporaryTerritory();

    document.getElementById("playButton").disabled = false;
    document.getElementById("stopButton").disabled = true;
    document.getElementById("pauseButton").disabled = true;

    Blockly.Themes.Hamster = Blockly.Theme.defineTheme("hamster", {
        'base': Blockly.Themes.Classic,
        'componentStyles': {
            'workspaceBackgroundColour': "rgb(255,245,235)",
            'toolboxBackgroundColour': "rgb(235,209,182)",
            'toolboxForegroundColour': "rgb(139, 69, 19)",
            'flyoutBackgroundColour': "rgb(230,190,138)",
            'flyoutForegroundColour': '#ccc',
            'flyoutOpacity': 1,
            'scrollbarColour': "rgb(235,209,182)",
            'insertionMarkerColour': '#fff',
            'insertionMarkerOpacity': 0.3,
            'scrollbarOpacity': 0.0,
            'cursorColour': '#d0d0d0',
            'blackBackground': '#333'
        }
    });

    workspace = Blockly.inject('blocklyDiv', {
        toolbox: document.getElementById('toolbox'),
        theme: Blockly.Themes.Hamster,
    });
    resizeBlocklyFunc();
    Blockly.svgResize(workspace);
    window.addEventListener('resize', onResizeFunc, false);

    // Touch Event Listeners...
    document.getElementById("verticalWall").addEventListener("touchend", touchEndFunc, false);
    document.getElementById("horizontalWall").addEventListener("touchend", touchEndFunc, false);
    document.getElementById("item").addEventListener("touchend", touchEndFunc, false);
    document.getElementById("trash").addEventListener("touchend", trashTouchEndFunc, false);
}

function drawBasicTerritory() {
    territory.fillStyle = "rgb(224,224,224)";
    territory.fillRect(0, 0, canvas.width, canvas.height);
    for (var i = 0; i < canvas.width; i += cellWidth) {
        for (var j = 0; j < canvas.height; j += cellHeight) {
            territory.beginPath();
            territory.strokeStyle = "rgb(139, 69, 19)";
            territory.strokeRect(i, j, cellWidth, cellHeight);
        }
    }
}

function initTerritory() {
    createCellContent();
    // fill Territory matrix
    for (var r = 0; r < row; r++) {
        for (var c = 0; c < column; c++) {
            territoryContent[r][c] = new CellContent();
        }
    }
    territoryContent[actorRow][actorColumn].setActor(true);
}

function placeActor() {
    if (currentX >= canvas.width) {
        currentX = cellWidth * column - (cellWidth / 2);
    } else if (currentX <= 0) {
        currentX = cellWidth / 2;
    } else {
        var c = Math.floor(currentX / cellWidth);
        currentX = cellWidth * c + (cellWidth / 2);
    }
    if (currentY >= canvas.height) {
        currentY = cellHeight * row - (cellHeight / 2);
    } else if (currentY <= 0) {
        currentY = cellHeight / 2;
    } else {
        var r = Math.floor(currentY / cellHeight);
        currentY = cellHeight * r + (cellHeight / 2);
    }

    // update actor position in Territory Content
    territoryContent[actorRow][actorColumn].setActor(false);
    actorRow = Math.floor(currentY / cellHeight);
    actorColumn = Math.floor(currentX / cellWidth);
    territoryContent[actorRow][actorColumn].setActor(true);
}

function drawActor() {
    if (territoryContent[actorRow][actorColumn].getItem()) {
        territory.drawImage(actorImage, currentX - 10, currentY - (actorImage.height / 2));
    } else {
        territory.drawImage(actorImage, currentX - (actorImage.width / 2), currentY - (actorImage.height / 2));
    }
}

function returnActorOnCanvas() {
    if (canvas.width < currentX || canvas.height < currentY) {
        currentX = 30;
        currentY = 25;
        actorRow = 0;
        actorColumn = 0;
       // territoryContent[actorRow][actorColumn].setWall(false);
        territoryContent[actorRow][actorColumn].setActor(true);
    }
}

function actorMouseEvents() {
    console.log("actorMouseEvents called!");
    canvas.addEventListener("touchmove", function (event) {
        console.log("actorMouseEvents touchmove called!");
        var touch = event.targetTouches[0];
        // Place element where the finger is
        var touchX = touch.pageX - this.offsetLeft;
        var touchY = touch.pageY - this.offsetTop;
        if (touchX >= (currentX - actorImage.width / 2) &&
            touchX <= (currentX + actorImage.width / 2) &&
            touchY >= (currentY - actorImage.height / 2) &&
            touchY <= (currentY + actorImage.height / 2)) {
            currentX = touch.pageX - this.offsetLeft;
            currentY = touch.pageY - this.offsetTop;
            drawBasicTerritory();
            drawTerritoryContent();
            drawActor();
            event.preventDefault();
        }
    }, false);
    canvas.addEventListener("touchend", function (event) {
        console.log("actorMouseEvents touchend called!");
        var c = Math.floor(currentX / cellWidth);
        var r = Math.floor(currentY / cellHeight);
        console.log("actorMouseEvents touchend canvas.width: ", canvas.width)
        console.log("actorMouseEvents touchend currentX: ", currentX)
        if (currentX > canvas.width || currentY > canvas.height || currentX < 0 || currentY < 0) {
            returnActorToPreviousPosition();
        } else {
            placeActor();
        }
        // document.getElementById("territoryId").style.cursor = "default";
        drawBasicTerritory();
        drawTerritoryContent();
        drawActor();
        event.preventDefault();

    }, false);
    canvas.onmousedown = function (e) {
        var mouseX = e.pageX - this.offsetLeft;
        var mouseY = e.pageY - this.offsetTop;
        if (mouseX >= (currentX - actorImage.width / 2) &&
            mouseX <= (currentX + actorImage.width / 2) &&
            mouseY >= (currentY - actorImage.height / 2) &&
            mouseY <= (currentY + actorImage.height / 2)) {
            isDraggable = true;
            document.getElementById("territoryId").style.cursor = "move";
        }
        //console.log("mouseX: ", mouseX, " mouseY: ", mouseY);
    };
    canvas.onmousemove = function (e) {
        if (isDraggable) {
            currentX = e.pageX - this.offsetLeft;
            currentY = e.pageY - this.offsetTop;
            var c = Math.floor(currentX / cellWidth);
            var r = Math.floor(currentY / cellHeight);

            document.getElementById("territoryId").style.cursor = "move";
            drawBasicTerritory();
            drawTerritoryContent();
            drawActor();
        }
    };
    canvas.onmouseup = function (e) {
        if (isDraggable) {
            var c = Math.floor(currentX / cellWidth);
            var r = Math.floor(currentY / cellHeight);
            placeActor();
            document.getElementById("territoryId").style.cursor = "default";
            drawBasicTerritory();
            drawTerritoryContent();
            drawActor();
        }
        isDraggable = false;
    };
    canvas.onmouseout = function (e) {
        if (isDraggable) {
            document.getElementById("territoryId").style.cursor = "default";
            returnActorToPreviousPosition();
            drawBasicTerritory();
            drawTerritoryContent();
            drawActor();
        }
        isDraggable = false;
    };
}

function onSetNikiItems() {
    console.log("slider value: ", document.getElementById("number").value)
    nikiItems = parseInt(document.getElementById("number").value);
}

function setCellContent(r, c, position, wallPosition) {
    if (currentDraggableToCanvas == "horizontalWallImage") {
        console.log("northWall: ", territoryContent[r][c].getNorthWall(), " southWall: ", territoryContent[r][c].getSouthWall());
        if (wallPosition[0] == 'n') {
            if (!territoryContent[r][c].getNorthWall()) {
                territoryContent[r][c].setNorthWall(true);
                if (r > 0) {
                    territoryContent[r - 1][c].setSouthWall(true);
                }
                territory.drawImage(northWallImage, position[0] - (northWallImage.width / 2), position[1] - (northWallImage.height / 2));
            }
        } else if (wallPosition[0] == 's') {
            if (!territoryContent[r][c].getSouthWall()) {
                territoryContent[r][c].setSouthWall(true);
                if (r + 1 < row) {
                    territoryContent[r + 1][c].setNorthWall(true);
                }
                territory.drawImage(southWallImage, position[0] - (southWallImage.width / 2), position[1] - (southWallImage.height / 2));
            }
        }
    }
    if (currentDraggableToCanvas == "verticalWallImage") {
        console.log("westWall: ", territoryContent[r][c].getWestWall(), " eastWall: ", territoryContent[r][c].getEastWall());
        if (wallPosition[1] == 'w') {
            if (!territoryContent[r][c].getWestWall()) {
                territoryContent[r][c].setWestWall(true);
                if (c > 0) {
                    territoryContent[r][c - 1].setEastWall(true);
                }
                territory.drawImage(westWallImage, position[0] - (westWallImage.width / 2), position[1] - (westWallImage.height / 2));
            }
        } else if (wallPosition[1] == 'e') {
            if (!territoryContent[r][c].getEastWall()) {
                territoryContent[r][c].setEastWall(true);
                if (c + 1 < column) {
                    territoryContent[r][c + 1].setWestWall(true);
                }
                territory.drawImage(eastWallImage, position[0] - (eastWallImage.width / 2), position[1] - (eastWallImage.height / 2));
            }
        }
    }
    if (currentDraggableToCanvas == "itemImage") {
        territoryContent[r][c].setItem(true);
        territoryContent[r][c].incrementItem();
        if (territoryContent[r][c].getActor()) {
            drawBasicTerritory();
            drawTerritoryContent();
            drawActor();
        } else {
            territory.drawImage(itemImage, position[0] - (itemImage.width / 2), position[1] - (itemImage.height / 2));
            drawItemAmount(r, c, position);
        }
        console.log("itemAmount: ", territoryContent[r][c].getItemAmount());
    }
    currentDraggableToCanvas = " ";
    drawBasicTerritory();
    drawTerritoryContent();
    drawActor();
    //console.log(territoryContent);
}

function drawItemAmount(r, c, position) {
    territory.fillStyle = "white";
    territory.fillRect(position[0] - 7, position[1] - 3, 15, 15);
    territory.fillStyle = "black";
    territory.font = "14px Comic Sans MS";
    territory.textAlign = "center";
    territory.fillText(territoryContent[r][c].getItemAmount(), position[0], position[1] + 10);
}

function drawTerritoryContent() {
    for (var r = 0; r < row; r++) {
        for (var c = 0; c < column; c++) {
            var x = cellWidth * c + (cellWidth / 2);
            var y = cellHeight * r + (cellHeight / 2);
            if (territoryContent[r][c].getNorthWall()) {
                territory.drawImage(northWallImage, x - (northWallImage.width / 2), y - (northWallImage.height / 2));
            }
            if (territoryContent[r][c].getSouthWall()) {
                territory.drawImage(southWallImage, x - (southWallImage.width / 2), y - (southWallImage.height / 2));
            }
            if (territoryContent[r][c].getWestWall()) {
                territory.drawImage(westWallImage, x - (westWallImage.width / 2), y - (westWallImage.height / 2));
            }
            if (territoryContent[r][c].getEastWall()) {
                territory.drawImage(eastWallImage, x - (eastWallImage.width / 2), y - (eastWallImage.height / 2));
            }
            if (territoryContent[r][c].getItem()) {
                if (territoryContent[r][c].getActor()) {
                    territory.drawImage(itemImage, x - (cellWidth / 2), y - (itemImage.height / 2));
                    x = x - (cellWidth / 2) + 7;
                    drawItemAmount(r, c, [x, y]);
                } else {
                    territory.drawImage(itemImage, x - (itemImage.width / 2), y - (itemImage.height / 2));
                    drawItemAmount(r, c, [x, y]);
                }
            }
        }
    }
}

function deleteElement(positionX, positionY) {

    var c = Math.floor(positionX / cellWidth);
    var r = Math.floor(positionY / cellHeight);

    // Erweiterung möglich, dass nur eine Wand oder nur ein Item gelöscht wird

    if (territoryContent[r][c].getNorthWall()) {
        territoryContent[r][c].setNorthWall(false);
        if (r > 0) {
            territoryContent[r - 1][c].setSouthWall(false);
        }
    }
    if (territoryContent[r][c].getSouthWall()) {
        territoryContent[r][c].setSouthWall(false);
        if (r + 1 < row) {
            territoryContent[r + 1][c].setNorthWall(false);
        }
    }
    if (territoryContent[r][c].getWestWall()) {
        territoryContent[r][c].setWestWall(false);
        if (c > 0) {
            territoryContent[r][c - 1].setEastWall(false);
        }
    }
    if (territoryContent[r][c].getEastWall()) {
        territoryContent[r][c].setEastWall(false);
        if (c + 1 < column) {
            territoryContent[r][c + 1].setWestWall(false);
        }
    }
    territoryContent[r][c].setItemAmount(0);
    drawBasicTerritory();
    drawTerritoryContent();
    drawActor();
    console.log("CellContent at [", r, ",", c, "] deleted");
    currentDraggableToCanvas = " ";
}
