import { world } from "mojang-minecraft"

function setLinkedTransmitter(entity, tag, linkedTransmitter) {
    entity.removeTag(tag)
    entity.addTag(`linkedTransmitter:${linkedTransmitter}`)
}

function getTagByStartsWith(entity, startsWithStr) {
    for (const tag of entity.getTags()) {
        if (tag.startsWith(startsWithStr)) {
            return tag
        }
    }
}

world.events.dataDrivenEntityTriggerEvent.subscribe((event) => {
    if (event.entity.id == "bme:power_transmitter_entity") {
        if (event.id == "minecraft:entity_spawned") {
            event.entity.addTag(`${event.entity.location.x} ${event.entity.location.y} ${event.entity.location.z}`)
            event.entity.addTag("linkedTransmitter:none")
        } else if (event.id == "bme:powered") {
            event.entity.addTag("powered")
        } else if (event.id == "bme:powered2") {
            event.entity.addTag("powered2")
        } else if (event.id == "bme:unpowered") {
            try { event.entity.removeTag("powered") } catch { }
            try { event.entity.removeTag("powered2") } catch { }
        } else if (event.id == "bme:energy" || event.id == "bme:energy2") {
            try {
                if (event.id == "bme:energy") { event.entity.runCommand("fill ~ ~-1 ~ ~ ~-1 ~ vatonage:powered_cable 0 replace vatonage:power_cable") } // returns an error if it fails, so the line under it won't run
                if (event.id == "bme:energy2") { event.entity.runCommand("fill ~ ~-1 ~ ~ ~-1 ~ vatonage:powered_cable2 0 replace vatonage:power_cable") } // returns an error if it fails, so the line under it won't run
                event.entity.runCommand("event entity @s bme:unpowered")
            } catch {
                if (!event.entity.hasTag("linkedTransmitter:none")) {
                    try {
                        if (event.entity.hasTag("powered2")) {
                            event.entity.runCommand(`event entity @e[type=bme:power_transmitter_entity,tag=!powered,tag=!powered2,tag="${getTagByStartsWith(event.entity, "linkedTransmitter:").split(":")[1]}"] bme:powered2`)
                        } else {
                            event.entity.runCommand(`event entity @e[type=bme:power_transmitter_entity,tag=!powered,tag=!powered2,tag="${getTagByStartsWith(event.entity, "linkedTransmitter:").split(":")[1]}"] bme:powered`)
                        }

                        event.entity.runCommand("event entity @s bme:unpowered")
                    } catch { }
                }
            }
        } else if (event.id == "bme:link_to") {
            let tag = getTagByStartsWith(event.entity, "bmeptlink:")
            let newTransmitter = tag.split(":")[1]
            if (newTransmitter != `${event.entity.location.x} ${event.entity.location.y} ${event.entity.location.z}`) {
                setLinkedTransmitter(event.entity, getTagByStartsWith(event.entity, "linkedTransmitter:"), newTransmitter)
                event.entity.removeTag(tag)
                event.entity.runCommand(`tellraw @p { "rawtext": [ { "text":"Successfully linked power transmitter at ${newTransmitter}" } ] }`)
            } else {
                event.entity.runCommand(`tellraw @p { "rawtext": [ { "text":"Cannot link transmitter to itself!" } ] }`)
            }
        } else if (event.id == "bme:link_from") {
            event.entity.runCommand(`tag @p add "bmeptlink:${event.entity.location.x} ${event.entity.location.y} ${event.entity.location.z}"`)
            event.entity.runCommand(`tellraw @p { "rawtext": [ { "text":"Power transmitter ready to link" } ] }`)
        }
    }
})

world.events.entityHit.subscribe((event) => {
    if (event.entity.id == "minecraft:player" && event.hitBlock && (event.hitBlock.id == "bme:power_transmitter_powered" || event.hitBlock.id == "bme:power_transmitter_unpowered" || event.hitBlock.id == "bme:power_transmitter_powered2")) {
        let pos = `${event.hitBlock.x} ${event.hitBlock.y} ${event.hitBlock.z}`
        if (event.entity.isSneaking) {
            event.entity.runCommand(`execute @s ${pos} event entity @e[type=bme:power_transmitter_entity,c=1] bme:despawn`)
            event.entity.runCommand(`setblock ${pos} air`)
            event.entity.runCommand(`give @s bme:power_transmitter`)
        } else {
            for (const tag of event.entity.getTags()) {
                if (tag.startsWith("bmeptlink:")) {
                    event.entity.removeTag(tag)
                    event.entity.runCommand(`execute @s ${pos} tag @e[type=bme:power_transmitter_entity,c=1] add "${tag}"`)
                    event.entity.runCommand(`execute @s ${pos} event entity @e[type=bme:power_transmitter_entity,c=1] bme:link_to`)
                    return
                }
            }

            event.entity.runCommand(`execute @s ${pos} event entity @e[type=bme:power_transmitter_entity,c=1] bme:link_from`)
        }
    }
})

world.events.blockBreak.subscribe((event) => {
    if (event.brokenBlockPermutation.type.id == "bme:power_transmitter_powered" || event.brokenBlockPermutation.type.id == "bme:power_transmitter_unpowered" || event.brokenBlockPermutation.type.id == "bme:power_transmitter_powered2") {
        event.player.runCommand(`execute @s ${event.block.x} ${event.block.y} ${event.block.z} event entity @e[type=bme:power_transmitter_entity,c=1] bme:despawn`)
    }
})