import { EntityComponentTypes, system, world } from '@minecraft/server';
import { ejectMobs } from './automatic';
import { trainFamily } from './trainsAddOn';

function whistle(player, whistleType) {
    player.dimension.playSound(`ta_${whistleType}_whistle`,player.location)
    player.dimension.getEntities({families:[trainFamily],location:player.location,maxDistance:6,closest:1}).forEach(car => {
        ejectMobs(car, whistleType === "wood" ? 1 : Number.MAX_VALUE)
    })
}

function isWhistleItem(itemStack) {
    switch(itemStack.typeId) {
        case "lifeboat_ta:wooden_train_whistle":
            return "wood"
        case "lifeboat_ta:metal_train_whistle":
            return "metal"
        default:
            return undefined
    }
}

function isOurTrain(entity) {
    const familyComponent = entity.getComponent(EntityComponentTypes.TypeFamily)
    if (familyComponent && familyComponent.hasTypeFamily(trainFamily)) return true
    else return false
}

world.afterEvents.itemUse.subscribe(useEvent => {
    const player = useEvent.source
    const whistleType = isWhistleItem(useEvent.itemStack)
    const riding = player.getComponent(EntityComponentTypes.Riding)
    // if riding a train, skip this whistle call; it will be handled by playerInteractWithEntity
    if (riding && isOurTrain(riding.entityRidingOn)) return
    if (whistleType && player) whistle(player, whistleType)
})

// this is how we get the whistle to still activate when interacting with a train car; for some reason
// interacting with a train car while holding a whistle doesn't trigger itemUse ¯\_(ツ)_/¯
world.beforeEvents.playerInteractWithEntity.subscribe(interactEvent => {
    if (!isOurTrain(interactEvent.target)) return
    const item = interactEvent.itemStack
    if (item) {
        const whistleType = isWhistleItem(item)
        if (whistleType) system.run(() => whistle(interactEvent.player, whistleType))
    }
})