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

export class StarFactory {
    scene: PlayScene;

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

    create(group: Phaser.Physics.Arcade.Group) {
        const star = new Star(this.scene);
        group.add(star);
        return star;
    }
}

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

    constructor(scene: PlayScene) {
        const x = 0;
        const y = 0;
        super(scene, x, y, "star");
        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(120, 120)
            .setOffset(-5, 12)
            .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 = [350 * (this.scene.sky?.scaleFactors.height || 1), 410 * (this.scene.sky?.scaleFactors.height || 1)];
        const starHeight = possibleHeight[Math.floor(Math.random() * 2)]

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

        const distance = Phaser.Math.Between(this.scene.scale.width, this.scene.scale.width * 2);
        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 Star
        this.setDisplaySize(width * scaleFactor, height * scaleFactor);
    }

    update() {

    }
}
