import { Player } from '../characters/player.js';
import { Camera } from '../misc/cameras.js';
import { NNBoy } from '../characters/99boy.js';
import { Interface } from '../interface.js';
 
export class Gulch extends Phaser.Scene {

    constructor() {
        super({ key: 'Gulch' });

        this.cameras;
        this.player;
        this.cursors = null;
        this.wide = 1600;
        this.tall = 900;
        this.topBound = 1100;
        this.leftBound = 800;
    }

    preload() {
        this.load.image('gulch-tiles', 'assets/gulch-tiles.png');
        this.load.image('heart-full', 'assets/heart-full.png');  
        this.load.image('heart-empty', 'assets/heart-empty.png');  
        this.load.image('heart-upgrade', 'assets/heart-upgrade.png');    
        this.load.tilemapTiledJSON('gulchMap', 'assets/gulch.json'); 
        this.load.spritesheet('player-tiles', 'assets/player-tiles.png', {
            frameWidth: 100, 
            frameHeight: 100 
        });
        this.load.spritesheet('99boy-tiles', 'assets/99boy-tiles.png', {
            frameWidth: 100, 
            frameHeight: 100 
        });
        this.load.spritesheet('gulchMap-tiles', 'assets/gulch-tiles.png', {
            frameWidth: 100, 
            frameHeight: 100 
        });

        // Level Music
        this.load.audio('gulchMusic', 'assets/music/gulch.mp3');
        // Player Sounds
        this.load.audio('gunShot', 'assets/sounds/gun-shot.mp3');
        this.load.audio('axeThrow', 'assets/sounds/axe.mp3');
        this.load.audio('health-pickup', 'assets/sounds/health-pickup.mp3');
        this.load.audio('player-damage', 'assets/sounds/player-damage.mp3');
        // 99 Boy Sounds
        this.load.audio('99boy-defeat-0', 'assets/sounds/zombie-death-1.mp3');
        this.load.audio('99boy-defeat-1', 'assets/sounds/zombie-death-2.mp3');
        this.load.audio('99boy-defeat-2', 'assets/sounds/zombie-death-3.mp3');
        this.load.audio('crumple', 'assets/sounds/crumple.mp3');
        this.load.audio('glass-break', 'assets/sounds/glass-break.mp3');
        this.load.audio('swoosh', 'assets/sounds/swoosh.mp3');
    }

    create() {                
        // Load the map and tileset
        const gulchMap = this.make.tilemap({ key: 'gulchMap' });
        const gulchTiles = gulchMap.addTilesetImage('gulch-tiles', 'gulch-tiles');
        const NNTiles = gulchMap.addTilesetImage('99boy-tiles', '99boy-tiles');
        const mainLayer = gulchMap.createLayer('main', gulchTiles, 0, 0)
            .setCollisionByProperty({ collides: true });
        const objectsLayer = gulchMap.createLayer('objects', gulchTiles, 0, 0)
            .setCollisionByProperty({ collides: true });
        const enemiesLayer = gulchMap.getObjectLayer('enemies');
        const zoneLayer = gulchMap.getObjectLayer('zone');

        // Show Score
        this.interface = new Interface(this);
        this.interface.showScore();

        // Add a player
        this.player = new Player(this, this.game.globalState.startGulchX, this.game.globalState.startGulchY);
        this.player.healthBars(true, 1, 3);

        zoneLayer.objects.forEach(object => {
            if (object.name === '99Dungeon') {
                const NNDungeon = this.add.rectangle(object.x, object.y, object.width, object.height);
                this.NNDungeon = this.physics.add.existing(NNDungeon);
            }
        });

        // Add Enemies
        this.enemies = this.physics.add.group({
            classType: NNBoy,
            runChildUpdate: true
        });
        enemiesLayer.objects.forEach(object => {
            let a99Boy = this.enemies.create(object.x-50, object.y-50, '99boy-tiles', object.gid-101);
            if (object.properties) {
                object.properties.forEach(prop => {
                    if (prop.name === 'patrolX') {
                        let to = object.x + prop.value;
                        if (to < object.x) {
                            a99Boy.setPatrolX(to, object.x);
                        } else {
                            a99Boy.setPatrolX(object.x, to);
                        }
                    }
                    if (prop.name === 'patrolY') {
                        let to = object.y + prop.value;
                        if (to < object.y) {
                            a99Boy.setPatrolY(to, object.y);
                        } else {
                            a99Boy.setPatrolY(object.y, to);
                        }
                    }
                    if (prop.name === 'fire') {
                        a99Boy.shoots = true;
                        a99Boy.bottleReload = prop.value;
                    }
                    if (prop.name === 'speed') {
                        a99Boy.speed = prop.value;
                    }
                    if (prop.name === 'garbage') {
                        a99Boy.garbage = prop.value;
                    }
                    if (prop.name === 'fastShot' && prop.value === true) {
                        a99Boy.bottleReload = 2000;
                        a99Boy.bottleReloadVariance = 500;
                    }
                });
            }
        });

        // Create a group for bullets
        this.bullets = this.physics.add.group();
        this.bottles = this.physics.add.group();
        this.axes = this.physics.add.group();
        this.hearts = this.physics.add.group();

        // Input
        this.cursors = this.input.keyboard.createCursorKeys();

        this.physics.add.collider(this.player, mainLayer);
        this.physics.add.collider(this.player, objectsLayer);
        this.physics.add.collider(this.enemies, mainLayer);
        this.physics.add.collider(this.enemies, objectsLayer);
        this.physics.add.collider(this.player, this.enemies, (player, enemy) => {
            player.takeDamage();
        });
        this.physics.add.collider(this.player, this.NNDungeon, (player, zone) => {
            this.bgMusic.stop();
            this.scene.start('NNDungeon');
        });

        // Collision between bullets and enemies
        this.physics.add.collider(this.bullets, this.enemies, (bullet, enemy) => {
            // Handle collision here (e.g., damage the enemy or destroy the bullet)
            bullet.destroy();
            enemy.takeDamage(1); // Assuming your NNBoy class has a takeDamage function
        });

        this.physics.add.overlap(this.axes, this.enemies, (axe, enemy) => {
            // Handle collision here (e.g., damage the enemy or destroy the bullet)
            axe.destroy();
            enemy.takeDamage(1); // Assuming your NNBoy class has a takeDamage function
        });

        this.physics.add.collider(this.player, this.bottles, (player, bottle) => {
            player.takeDamage(bottle);
            bottle.destroy();
        });

        this.physics.add.collider(this.player, this.hearts, (player, heart) => {
            player.addHealth(1);
            heart.destroy();
        });

        // Add level heart upgrade
        if (this.game.globalState.hasInventory('gulch-heart') === 0) {
            this.upgrade = this.physics.add.image(5200, 5800, 'heart-upgrade').setScale(0.2);
            this.physics.add.collider(this.player, this.upgrade, (player, upgrade) => {
                this.game.globalState.addToInventory('gulch-heart', 1);
                this.player.maxHearts ++;
                this.player.numHearts ++;
                this.game.globalState.maxHearts = this.player.maxHearts;
                this.game.globalState.hearts = this.player.numHearts;
                this.player.updateHealth();
                upgrade.destroy();                
            });
        }

        // Add Protech Lock
        if (this.game.globalState.hasInventory('proEdgeLock') === 0) {
            this.proEdgeLock = this.physics.add.sprite(4450, 4250, 'gulchMap-tiles', 60);
            this.proEdgeLock.setImmovable(true);
            this.physics.add.collider(this.player, this.proEdgeLock, (player, lock) => {
                if (this.game.globalState.hasInventory('proEdgeKey') > 0) {
                    this.game.globalState.addToInventory('proEdgeLock', 1);
                    this.proEdgeLock.destroy();
                }
            });
        }

        //this.cameras.main.setScroll(800, 1100);
        this.cameras.main.setBounds(0, 3600, 1600, 900);
        
        // Background Music
        this.bgMusic = this.sound.add('gulchMusic', { volume: 0.5 });
        this.bgMusic.loop = true;
        this.bgMusic.play();
    }

    update(time, delta) {
        this.player.update();

        const onBounds = this.cameras.main.getBounds();
        if (this.player.body.y <= onBounds.y) {
            this.cameras.main.setBounds(onBounds.x, onBounds.y-900, 1600, 900);
        }
        if (this.player.body.y >= onBounds.y+900) {
            this.cameras.main.setBounds(onBounds.x, onBounds.y+900, 1600, 900);
        }
        if (this.player.body.x <= onBounds.x) {
            this.cameras.main.setBounds(onBounds.x-1600, onBounds.y, 1600, 900);
        }
        if (this.player.body.x >= onBounds.x+1600) {
            this.cameras.main.setBounds(onBounds.x+1600, onBounds.y, 1600, 900);
        }
    }
}