import * as mc from "@minecraft/server"

const maxPage = 13
mc.world.afterEvents.entityHitEntity.subscribe(data => {

    const source = data.damagingEntity, entity = data.hitEntity

    if (entity.typeId !== "tp_pw:guide_book") { return; }
    if (entity.getDynamicProperty("tp_pw:finalized") !== undefined) { return; }
    onHit(entity, source)



})

mc.system.afterEvents.scriptEventReceive.subscribe(data => {

    const id = data.id, entity = data.sourceEntity

    if (id === "tp_pw:next_page") {
        
        if (entity.getDynamicProperty("tp_pw:finalized") !== undefined) { return; }
        nextPage(entity)
    
    
    }
    if (id === "tp_pw:back_page") {
        
        if (entity.getDynamicProperty("tp_pw:finalized") !== undefined) { return; }
        backPage(entity)
    
    
    }
    if (id === "tp_pw:start") {
        
        mc.world.setDynamicProperty("tp_pw:camera", true)
        mc.world.setDynamicProperty("tp_pw:sound", true)
    
    
    }


})

/** @param { mc.Entity } entity */
function nextPage(entity) {

    entity.getDynamicProperty("tp_pw:delay") === undefined ? entity.setDynamicProperty("tp_pw:delay", false): null
    if (entity.getDynamicProperty("tp_pw:delay") !== false) { return; }
    const page = entity.getProperty("tp_pw:page")
    if (page !== maxPage) {

        entity.setProperty("tp_pw:page", entity.getProperty("tp_pw:page") + 1)
        mc.world.playSound("item.book.page_turn", entity.location, { "pitch": 1.2 })
        entity.setDynamicProperty("tp_pw:delay", true)
        mc.system.runTimeout(() => {
            
            entity.setDynamicProperty("tp_pw:delay", false)
        }, 0.2*20)
    }
}
/** @param { mc.Entity } entity */
function backPage(entity) {

    if (entity.getDynamicProperty("tp_pw:delay") !== false) { return; }
    const page = entity.getProperty("tp_pw:page")
    if (page !== 1) {

        entity.setProperty("tp_pw:page", entity.getProperty("tp_pw:page") - 1)
        mc.world.playSound("item.book.page_turn", entity.location, { "pitch": 1.2 })
        entity.setDynamicProperty("tp_pw:delay", true)
        mc.system.runTimeout(() => {
            
            entity.setDynamicProperty("tp_pw:delay", false)


        }, 0.2*20)
    
    }


}

/** @param { mc.Entity } entity */
/** @param { mc.Player } source */
function onHit(entity, source) {

    entity.playAnimation("close")
    entity.setDynamicProperty("tp_pw:finalized", true)
    mc.world.playSound("item.book.page_turn", entity.location, { "pitch": 0.8 })
    mc.world.playSound("tp_pw:book_spawn", entity.location, { "pitch": 0.8 })
    mc.system.runTimeout(() => {
    
        /** @type { mc.EntityInventoryComponent } */
        const inventory = source.getComponent("inventory")
        inventory.container.addItem(new mc.ItemStack("tp_pw:guide_book"))
        entity.remove()


    }, 1.5*20)


}