const MOWER_SPEED = 150;
const SPIDER_SPEED = 100;

function setMowerDirection(mower)
{
    mower.setVelocity(0);
    switch (mower.orientation) {
        case "up":
            mower.setVelocityY(-MOWER_SPEED);
            break;
        case "down":
            mower.setVelocityY(MOWER_SPEED);
            break;
        case "left":
            mower.setVelocityX(-MOWER_SPEED);
            break;
        case "right":
            mower.setVelocityX(MOWER_SPEED);
            break;
    }
    mower.anims.play("lawnmower-" + mower.orientation);
}

var config = {
    type: Phaser.AUTO,
    width: 336,
    height: 240,
    zoom: 2,
    backgroundColor: "#00AA00",
    pixelArt: true,
    physics: {
        default: 'arcade',
        arcade: {
            gravity: {y: 0}
        }

    },
    scene: {
        preload: preload,
        create: create,
        update: update,
    }
};

var game = new Phaser.Game(config);
var arrowkeys;
var map;
var worryspider;
var gameOver;
var lawnmowers = [];

function preload()
{
    this.load.path = "assets/";
    // This is our hero
    this.load.spritesheet("worryspider", "worryspider.png",
                          {frameWidth: 16, frameHeight: 16});
    // These are her enemies
    this.load.spritesheet("lawnmower", "lawnmower.png",
                          {frameWidth: 16, frameHeight: 16});
    // This is his prize
    this.load.image("apple", "apple.png");
    // This is their arena
    this.load.tilemapTiledJSON("garden", "garden.json");
    this.load.image("gardentiles", "gardentiles.png");
    // This is NOT blood
    this.load.image("blood", "heart.png");
}

function create()
{
    // Setup tilemap
    map = this.make.tilemap({
        key: "garden",
        tileWidth: 16, tileHeight: 16
    });
    var tileset = map.addTilesetImage("tiles", "gardentiles");
    map.createStaticLayer("Grass", tileset);
    var obstacles = map.createStaticLayer("Obstacles", tileset);
    map.setCollision([1,2]); // enable collision on this layer
    map.createStaticLayer("Scenery", tileset);

    // Set up our hero
    // XXX: MY GOD, WHAT HAVE I DONE
    [["worryspider-idle", 0, 3],
     ["worryspider-down", 5, 8],
     ["worryspider-up", 10, 13],
     ["worryspider-left", 15, 19],
     ["worryspider-right", 20, 24]]
        .map(function(anim) {return (function (key, start, end) {
            return {
                key: key,
                frames: this.anims.generateFrameNumbers("worryspider", {start: start, end: end}),
                frameRate: 12,
                repeat: -1
            }
        }).apply(this, anim);}, this)
        .forEach(function(anim) {this.anims.create(anim)}, this);
    worryspider = this.physics.add.sprite(map.widthInPixels / 2, map.heightInPixels / 2, "worryspider");
    this.physics.add.collider(worryspider, obstacles);

    // Set up our enemies
    // can't believe i went through all the effort above to simplify this code just to duplicate it. smdh@self
    [["lawnmower-down", 0, 1],
     ["lawnmower-up", 2, 3],
     ["lawnmower-left", 4, 5],
     ["lawnmower-right", 6, 7]]
        .map(function(anim) {return (function (key, start, end) {
            return {
                key: key,
                frames: this.anims.generateFrameNumbers("lawnmower", {start: start, end: end}),
                frameRate: 12,
                repeat: -1
            }
        }).apply(this, anim);}, this)
        .forEach(function(anim) {this.anims.create(anim)}, this);
    for (const lawnmower of map.getObjectLayer("Lawnmowers").objects) {
        let newmower = this.physics.add.sprite(lawnmower.x + 8, lawnmower.y + 8, "lawnmower");
        newmower.orientation = lawnmower.properties[0].value;
        setMowerDirection(newmower);
        lawnmowers.push(newmower);
    }
    // This callback makes lawnmowers bounce off walls
    this.physics.add.collider(lawnmowers, obstacles, function(mower, obs) {
        mower.setVelocity(0);
        switch (mower.orientation) {
            case "up":
                mower.orientation = "down";
                break;
            case "down":
                mower.orientation = "up";
                break;
            case "right":
                mower.orientation = "left";
                break;
            case "left":
                mower.orientation = "right";
                break;
        }
        setMowerDirection(mower);
    });
    this.physics.add.collider(worryspider, lawnmowers, function(ws) {
        gameOver = true;
        var position = ws.body.center;
        this.add.particles("blood", 0, {
            x: position.x,
            y: position.y,
            radial: true,
            speed: 200,
            lifespan: 1000,
        });
        ws.destroy();
        this.time.delayedCall(2000, function() {
            this.scene.start();
        }, [], this);
    }, () => true, this);

    // Create controls
    cursors = this.input.keyboard.createCursorKeys();
}

function update(time, delta)
{
    if (gameOver) {
        return;
    }
    // Worryspider's movement code
    worryspider.body.setVelocity(0);
    if (cursors.up.isDown) {
        worryspider.body.setVelocityY(-SPIDER_SPEED);
    } else if (cursors.down.isDown) {
        worryspider.body.setVelocityY(SPIDER_SPEED);
    }
    if (cursors.left.isDown) {
        worryspider.body.setVelocityX(-SPIDER_SPEED);
    } else if (cursors.right.isDown) {
        worryspider.body.setVelocityX(SPIDER_SPEED);
    }

    if (cursors.left.isDown) {
        worryspider.anims.play("worryspider-left", true);
    } else if (cursors.right.isDown) {
        worryspider.anims.play("worryspider-right", true);
    } else if (cursors.up.isDown) {
        worryspider.anims.play("worryspider-up", true);
    } else if (cursors.down.isDown) {
        worryspider.anims.play("worryspider-down", true);
    } else {
        worryspider.anims.play("worryspider-idle", true);
    }
}
