import PlayScene from "../scenes/PlayScene";

export class CogFactory {
    scene: PlayScene;

    constructor(scene: PlayScene) {
        this.scene = scene;
    }

    create(obstaclesGroup: Phaser.Physics.Arcade.Group) {
        const cog = new Cog(this.scene);
        obstaclesGroup.add(cog);
        return cog;
    }
}

export class Cog extends Phaser.Physics.Arcade.Sprite {
    scene: PlayScene;

    constructor(scene: PlayScene) {
        const x = 0;
        const y = 0;
        super(scene, x, y, "cog");
        this.scene = scene;
        scene.add.existing(this);
        scene.physics.add.existing(this);

        this.init();
        this.scene.events.on(Phaser.Scenes.Events.UPDATE, this.update, this);
    }

    init() {
        this
            .setOrigin(0, 1)
            .setCollideWorldBounds(true)
            .setBodySize(180, 180)
            .setOffset(-15, 30)
            .setDepth(2);

        // Handle resizing
        this.scene.scale.on('resize', this.scaleToFit, this);
        this.scene.scale.on('resize', this.positionOnSky, this);

        this.scaleToFit();
        this.positionOnSky();
    }

    positionOnSky() {
        const gameHeight = this.scene.scale.height;
        const possibleHeight = [80 * (this.scene.sky?.scaleFactors.height || 1), 170 * (this.scene.sky?.scaleFactors.height || 1)];
        const cogHeight = possibleHeight[Math.floor(Math.random() * 2)]

        // Position Cog at the bottom of the scaled background
        const skyHeight = this.scene.scale.height;
        const y = (gameHeight - (gameHeight - skyHeight)) - cogHeight; // Slight offset for alignment
        this.setY(y - 10);

        const distance = Phaser.Math.Between(this.scene.scale.width, this.scene.scale.width * 1.8);
        this.setX(distance);
    }

    scaleToFit() {
        // Use the scale factor from the Sky class to maintain consistency
        const scaleFactor = this.scene.sky?.scaleFactors.height || 1;
        const width = 85;
        const height = 85;

        // Apply the scale factor to the Cog
        this.setDisplaySize(width * scaleFactor, height * scaleFactor);
    }

    update() {

    }
}
