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

export class Ground extends Phaser.GameObjects.TileSprite {
    scene: PlayScene;
    heightScaled: number = 0;
    scaleFactor: number = 0;

    constructor(scene: PlayScene) {
        const x = 0;
        const y = scene.gameHeight;
        const width = scene.gameWidth;
        const height = 16;
        super(scene, x, y, width, height, "ground");
        this.scene = scene;
        scene.add.existing(this);
        scene.physics.add.existing(this, false);

        // make ground immovable
        (this.body as Phaser.Physics.Arcade.Body).setImmovable(true);

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

    init() {
        this
            .setOrigin(0, 0)
            .setDepth(2);

        this.scaleToFit();
        // 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;

        // Position player at the bottom of the scaled background
        const skyHeightScaled = (this.scene.sky?.height || 1) * (this.scene.sky?.scaleFactors.height || 1);
        const y = gameHeight - (gameHeight - skyHeightScaled); // Slight offset for alignment
        this.setY(y - 10);
    }

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

    update() {
        // this.tilePositionX += (this.scene.gameSpeed * this.scene.gameSpeedModifier);
    }
}
