import { system, world, MinecraftDimensionTypes } from '@minecraft/server'

class WorldModel{
    constructor(){
        this.allPlayers = []
        this.backpackEntities = []
    }
    
    updateAllPlayers(){
        this.allPlayers = world.getAllPlayers()
    }

    updateAllBackpacks(){
        this.backpackEntities = []
        const dimensions = [MinecraftDimensionTypes.overworld, MinecraftDimensionTypes.nether, MinecraftDimensionTypes.theEnd]
        for(let dimension of dimensions){
            let bpEntities = world.getDimension(dimension).getEntities({type:"bps:container_entity_temp"})
            for(let bp of bpEntities){
                this.backpackEntities.push(bp)
            }
        }
    }

    addPlayer(player){
        this.allPlayers.push(player)
    }

    removePlayer(playerName){
        try{
            this.allPlayers = this.allPlayers.filter(player => player.name != playerName)
        }catch(e){
            console.warn(e)
        }
    }

    addBackpack(backpack){
        this.backpackEntities.push(backpack)
    }

    getAllBackpacks(){
        return this.backpackEntities
    }

    getBackpacksWithTag(tag) {
        return this.backpackEntities.filter(bpEntity => bpEntity.isValid() && bpEntity.hasTag(tag));
    }

    getAllPlayers(){
        return this.allPlayers
    }
}

const sharedWorldModel = new WorldModel();

export default sharedWorldModel;