import * as mc from '@minecraft/server';
import * as mcui from '@minecraft/server-ui';
import * as racoAPI from "./raco-API"

import "./wireless/remote"
//import "./catmullrom"
import "./andrielScripts/main";
import "./minhoScripts/main";
import './hero/main';
import "./andrielScripts/outros_item";
import * as transmitter from "./wireless/transmitter"
import * as receiver from "./wireless/receiver"
import * as button from "./wireless/button"
import * as lever from "./wireless/lever"
import * as pressurePlate from "./wireless/pressurePlate"
import * as lamp from "./wireless/lamp"
import * as enderHopper from "./hoppers/enderHopper"
import * as precisionHopper from "./hoppers/precisionHopper"
import * as leakyHopper from "./hoppers/leakyHopper"
import * as babyFilter from "./hoppers/babyFilter"
import * as randomHopper from "./hoppers/randomHopper"


import * as uncrafter from "./machines/uncrafter"
import * as basicMachines from "./machines/basicMachines"


import * as sensors from "./sensors/sensors"

import * as plates from "./plates/plates"

export function blockTick( data = mc.BlockComponentTickEvent){
    const block = data.block
    if (block?.typeId == 'vtng_rt:wireless_transmitter') transmitter.transmitterTick(block)
    if (block?.typeId == 'vtng_rt:wireless_receiver') receiver.receiverTick(block)
    if (block.typeId == 'vtng_rt:wireless_pressure_plate') pressurePlate.pressurePlateTick(block)
    if (block.typeId == 'vtng_rt:wireless_lamp') lamp.lampTick(block)
    if (block.typeId == 'vtng_rt:ender_hopper') enderHopper.enderHopperTick(block)
    if (block.typeId == 'vtng_rt:precision_hopper') precisionHopper.precisionHopperTick(block)
    if (block.typeId == 'vtng_rt:leaky_hopper') leakyHopper.leakyHopperTick(block)
    if (block.typeId == 'vtng_rt:baby_filter') babyFilter.babyFilterTick(block)
    if (block.typeId == 'vtng_rt:random_hopper') randomHopper.randomHopperTick(block)
    if (block.typeId == 'vtng_rt:uncrafter') uncrafter.uncrafterTick(block)
    if (block.typeId == 'vtng_rt:placer') basicMachines.placerTick(block)
    if (block.typeId == 'vtng_rt:breaker') basicMachines.breakerTick(block)
    if (block.typeId == 'vtng_rt:user') basicMachines.userTick(block)
    if (block.typeId == 'vtng_rt:saw') basicMachines.sawTick(block)
    if (block.typeId == 'vtng_rt:igniter') basicMachines.igniterTick(block)
    if (block.typeId == 'vtng_rt:filtered_observer') basicMachines.filteredObserverTick(block)
    if (block.typeId == 'vtng_rt:elevator') basicMachines.elevatorTick(block)
    if (block.typeId == 'vtng_rt:grow_sensor') sensors.growSensorTick(block)
    if (block.typeId == 'vtng_rt:eye_sensor') sensors.eyeSensorTick(block)
    if (block.typeId == 'vtng_rt:item_elevator') basicMachines.itemElevatorTick(block)
    if (block.typeId == 'vtng_rt:harvester') basicMachines.harvesterTick(block)
    if (block.typeId == 'vtng_rt:monster_sensor') sensors.monsterSensorTick(block)
    if (block.typeId == 'vtng_rt:trash_can') basicMachines.trashCanTick(block)
    if (block.typeId == 'vtng_rt:if_lamp') basicMachines.IFLampTick(block)
    if (block.typeId == 'vtng_rt:debugger_display') basicMachines.debuggerTick(block)
    if (block.typeId == 'vtng_rt:redstone_display') basicMachines.rDisplayTick(block)
    if (block.typeId == 'vtng_rt:adjustable_pulse_repeater') plates.adjRepeaterTick(block)
    if (block.typeId == 'vtng_rt:cross') plates.crossTick(block)
    if (block.typeId == 'vtng_rt:toggle_latch') plates.toggleTick(block)
    if (block.typeId == 'vtng_rt:clock') plates.clockTick(block)
    if (block.typeId == 'vtng_rt:counter') plates.counterTick(block)
    if (block.typeId == 'vtng_rt:randomizer') plates.randomizerTick(block)
    if (block.typeId == 'vtng_rt:pulser') plates.pulserTick(block)
}
export function blockInteract( data = mc.BlockComponentPlayerInteractEvent){
    const player = data.player
    const block = data.block
    const face = data.face
    const item = player?.getComponent('equippable')?.getEquipment("Mainhand")
    const faceLocation = data.faceLocation
    if (block.typeId == 'vtng_rt:wireless_transmitter') transmitter.transmitterInteract(player, block)
    if (block.typeId == 'vtng_rt:wireless_receiver') receiver.receiverInteract(player, block)
    if (block.typeId == 'vtng_rt:wireless_button') button.buttonInteract(player, block)
    if (block.typeId == 'vtng_rt:wireless_lever') lever.leverInteract(player, block)
    if (block.typeId == 'vtng_rt:wireless_pressure_plate') pressurePlate.pressurePlateInteract(player, block)
    if (block.typeId == 'vtng_rt:wireless_lamp') lamp.lampInteract(player, block)
    if (block.typeId == 'vtng_rt:user') basicMachines.userInteract(player, block)
    if (block.typeId == 'vtng_rt:filtered_observer') basicMachines.filteredObserverInteract(player, block)
    if (block.typeId == 'vtng_rt:redstone_display') basicMachines.rDisplayInteract(player, block)
    if (block.typeId == 'vtng_rt:adjustable_pulse_repeater') plates.adjRepeaterInteract(player, block)
    if (block.typeId == 'vtng_rt:clock') plates.clockInteract(player, block)
    if (block.typeId == 'vtng_rt:counter') plates.counterInteract(player, block)
    if (block.typeId == 'vtng_rt:pulser') plates.pulserInteract(player, block)
}

mc.world.beforeEvents.worldInitialize.subscribe(initEvent => {
    initEvent.blockComponentRegistry.registerCustomComponent('vtng_rt:ticking', {
        onTick: blockTick,
    }),
    initEvent.blockComponentRegistry.registerCustomComponent('vtng_rt:interact', {
        onPlayerInteract: blockInteract,
    })
    initEvent.blockComponentRegistry.registerCustomComponent("vtng_rt:copper_spikes", {
        onPlayerInteract: (({ block, dimension, player }) => {
            let equippable = player.getComponent('equippable')
            let itemHand = equippable.getEquipment('Mainhand')
            let loc = block.location
            if (itemHand?.typeId == "minecraft:honeycomb" && !block.typeId.includes('waxed_')) {
                block.setType("vtng_rt:waxed_" + block.typeId.replace('vtng_rt:', ''))
                dimension.spawnParticle('vtng_rt:copper_spikes_wax', { x: block.center().x, y: block.y, z: block.center().z })
                if (itemHand.amount > 1) {
                    itemHand.amount--
                    equippable.setEquipment("Mainhand", itemHand)
                }
                dimension.playSound('copper.wax.on', block.center())
                if (itemHand.amount == 1) {
                    equippable.setEquipment("Mainhand",)
                }
            }
            if (itemHand?.typeId.includes('_axe') && block.typeId.includes('waxed_')) {
                let durability = itemHand.getComponent('durability')
                block.setType(block.typeId.replace('waxed_', ''))
                dimension.spawnParticle('vtng_rt:copper_spikes_remove_wax', { x: block.center().x, y: block.y, z: block.center().z })
                dimension.playSound('copper.wax.off', block.center())
                if ((durability.maxDurability - durability.damage) > 1) {
                    durability.damage++
                    equippable.setEquipment("Mainhand", itemHand)
                }
                if ((durability.maxDurability - durability.damage) == 1) {
                    equippable.setEquipment("Mainhand",)
                    dimension.playSound('random.break', player.location)
                }
            }
            if (itemHand?.typeId.includes('_axe')){
                if (block?.typeId == 'vtng_rt:oxidized_copper_spikes') block.setType('vtng_rt:weathered_copper_spikes'),dimension.playSound('copper.wax.off', block.center()); else
                if (block?.typeId == 'vtng_rt:weathered_copper_spikes') block.setType('vtng_rt:exposed_copper_spikes'),dimension.playSound('copper.wax.off', block.center()); else
                if (block?.typeId == 'vtng_rt:exposed_copper_spikes') block.setType('vtng_rt:copper_spikes'),dimension.playSound('copper.wax.off', block.center());
            }
        }),

        onTick: (({ block, dimension }) => {
            let blockState = block.permutation.getState('vtng_rt:active')
            let damageBlocks = {
                "vtng_rt:copper_spikes": 9,
                "vtng_rt:exposed_copper_spikes": 7,
                "vtng_rt:weathered_copper_spikes": 5,
                "vtng_rt:oxidized_copper_spikes": 3
            };
            let faces = {
                'below': 'down',
                'north': 'north',
                'south': 'south',
                'east': 'east',
                'west': 'west'
            };

            let findBlock = false;

            for (let face of Object.keys(faces)) {
                let powerBlock = block[face]()
                let hasPower = powerBlock?.getRedstonePower()
                if (hasPower > 0) findBlock = true
                if (hasPower > 0 && blockState == false) {
                    dimension.playSound('tile.piston.in', block.center())
                    racoAPI.setPermutation(block, 'vtng_rt:active', true)
                    let [entity] = dimension.getEntitiesAtBlockLocation(block.above())
                    if (entity) entity.applyDamage(damageBlocks[block.typeId.replace('waxed_', '')]);
                    break;
                }
            };

            if (findBlock == false && blockState == true) for (let face of Object.keys(faces)) {
                let powerBlock = block[face]()
                let hasPower = block.getRedstonePower()
                if (hasPower == 0) {
                    dimension.playSound('tile.piston.out', block.center())
                    racoAPI.setPermutation(block, 'vtng_rt:active', false)
                    break;
                }
            };

        }),

        onEntityFallOn: (({ block, fallDistance, entity }) => {
            let damageBlocks = {
                "vtng_rt:copper_spikes": 9,
                "vtng_rt:exposed_copper_spikes": 7,
                "vtng_rt:weathered_copper_spikes": 5,
                "vtng_rt:oxidized_copper_spikes": 3
            };
            if (entity && block.permutation.getState('vtng_rt:active') == true) {
                entity.applyDamage(fallDistance * damageBlocks[block.typeId.replace('waxed_', '')])
            }
        }),

        onRandomTick: (({ block, dimension }) => {
            if (!block.typeId.includes('waxed_') && Math.random() < 0.1) {
                if (block.typeId == 'vtng_rt:copper_spikes') block.setType('vtng_rt:exposed_copper_spikes');
                if (block.typeId == 'vtng_rt:exposed_copper_spikes') block.setType('vtng_rt:weathered_copper_spikes');
                if (block.typeId == 'vtng_rt:weathered_copper_spikes') block.setType('vtng_rt:oxidized_copper_spikes');
            }
        })
    })
})

mc.world.afterEvents.playerPlaceBlock.subscribe((data)=>{
    const block = data.block
    if (block?.typeId == 'vtng_rt:rain_sensor'){
        block.dimension.spawnEntity(`vtng_rt:rain_sensor_entity`, {x:block.center().x, y:block.center().y+0.6, z:block.center().z})
    }
})

mc.world.afterEvents.playerSpawn.subscribe((data)=>{
    const player = data.player
    if (data.initialSpawn == true && !player.hasTag('jarecebeuoguide')){
        player.addTag('jarecebeuoguide')
        player.dimension.spawnItem(new mc.ItemStack('vtng_rt:redstone_guide'), player.location)
    }
})