import * as mc from "@minecraft/server"
import * as lib from "./lib"
import * as property from "./lib/property"

mc.world.afterEvents.entityHitEntity.subscribe(data => {

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

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



})

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

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

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


})

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

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

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

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

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


        }, 0.2*20)
    
    }


}

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

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


    }, 0.5*20)


}