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

world.afterEvents.playerSpawn.subscribe((event) => {
    //Check for faction selection   
    if (!event.player.hasTag("faction_selected")){
        world.sendMessage("No faction: " + event.player.name);
        PLAYER_SELECT_FACTION(event.player);
    }
})

world.afterEvents.itemUse.subscribe((event) => {

    //Faction Selection Book
    if (event.itemStack.typeId == "lotr:side_book"){
        PLAYER_SELECT_FACTION(event.source);
    }
})


function PLAYER_SELECT_FACTION(_player){
    
    //Remove existing faction_selected tag
    if (_player.hasTag("faction_selected")){      
        _player.removeTag("faction_selected");
        _player.triggerEvent("remove_faction");
    }

    //check for NPC Component
    if (!_player.hasComponent("minecraft:npc")){
        _player.runCommand("event entity @p minecraft:add_npc");
    }
    
    system.runTimeout(() => {
        _player.runCommandAsync("dialogue open @p @p select_sides");
    }, 20);

}