import { system, world } from "@minecraft/server"
import { ModalFormData } from "@minecraft/server-ui"

const property = "lifeboat_ta:speed_setting"

// manages the stored speed value for the given sign
export function speedSignData(signEntity) {

    function set(value) {
        signEntity.setProperty(property,value * 10)
    }

    function get() {
        return signEntity.getProperty(property) / 10
    }

    return {
        get: function() {
            return get()
        },
        set: function(value) {
            return set(value)
        }
    }
}

// it's a form
function speedForm(signEntity) {
    const form = new ModalFormData()
    const oldData = speedSignData(signEntity).get()
    const oldSetting = oldData * 10
    form.title({translate:"form.speed.title"})
    form.slider({translate:"form.speed.setting"}, 10, 50, 10, oldSetting)
    return form
}

// open form when player interacts with sign entity
world.beforeEvents.playerInteractWithEntity.subscribe(interactEvent => {
    if (interactEvent.target.typeId !== "lifeboat_ta:speed_sign") return
    system.run(() => {
        speedForm(interactEvent.target).show(interactEvent.player).then(response => {
            if (response.canceled) return
            speedSignData(interactEvent.target).set(response.formValues[0] / 10)
        })
    })
})