const Phaser = require('phaser');

class LineBox extends Phaser.GameObjects.Graphics {
    constructor(scene, x, y, width, height, colour, speed) {
        super(scene);
        this.colour = colour;
        this.x0 = x; this.x1 = x + width;
        this.y0 = y; this.y1 = y + height;
        const margin = Math.abs(Math.floor((this.x1 - this.x0) / 4));
        this.lineCoord = [this.x0 + margin, this.x1 - margin, this.y0, this.y0, 0];
        this.speed = speed;
    }

    update() {
        this.clear();

        let vertX = this.x1;
        let horizY = this.y0;
        const genLine = () => {
            switch (this.lineCoord[4]) {
                case 0:
                    if (this.lineCoord[1] < this.x1) return [1, 1, 0, 0, 0];
                    return [0, 0, 0, 0, 1];
                case 1:
                    if (this.lineCoord[0] < this.x1) return [1, 0, 0, 1, 1];
                    return [0, 0, 0, 0, 2];
                case 2:
                    if (this.lineCoord[3] < this.y1) return [0, 0, 1, 1, 2];
                    return [0, 0, 0, 0, 3];
                case 3:
                    horizY = this.y1;
                    if (this.lineCoord[2] < this.y1) return [-1, 0, 1, 0, 3];
                    return [0, 0, 0, 0, 4];
                case 4:
                    horizY = this.y1;
                    if (this.lineCoord[0] > this.x0) return [-1, -1, 0, 0, 4];
                    return [0, 0, 0, 0, 5];
                case 5:
                    horizY = this.y1;
                    vertX = this.x0;
                    if (this.lineCoord[1] > this.x0) return [0, -1, -1, 0, 5];
                    return [0, 0, 0, 0, 6];
                case 6:
                    vertX = this.x0;
                    if (this.lineCoord[2] >= this.y0) return [0, 0, -1, -1, 6];
                    return [0, 0, 0, 0, 7];
                case 7:
                    vertX = this.x0;
                    if (this.lineCoord[3] >= this.y0) return [0, 1, 0, -1, 7];
                    return [0, 0, 0, 0, 0];
                default: return false;
            }
        };
        for (let i = 0; i < this.speed; i += 1) {
            const delta = genLine();
            this.lineCoord = this.lineCoord.map((x, j) => {
                if (j < 4) return (x + delta[j]);
                return delta[j];
            });
        }
        this.lineStyle(5, this.colour, 1);
        this.lineBetween(this.lineCoord[0], horizY, this.lineCoord[1], horizY);
        this.lineBetween(vertX, this.lineCoord[2], vertX, this.lineCoord[3]);
    }
}

class LineGroup extends Phaser.GameObjects.Group {
    constructor(scene) {
        super(scene, { classType: LineBox, runChildUpdate: true });
    }
}

module.exports = { LineGroup, LineBox }