let LIT_TORCH_ITEM = 'hardcore_torches:lit_torch';
let LIT_TORCH_ITEM_WALL = 'hardcore_torches:lit_wall_torch';
let UNLIT_TORCH_ITEMS_WALL = ['hardcore_torches:unlit_wall_torch','hardcore_torches:smoldering_wall_torch','hardcore_torches:burnt_wall_torch','valhelsia_structures:doused_wall_torch'];
let UNLIT_TORCH_ITEMS = ['hardcore_torches:unlit_torch','hardcore_torches:smoldering_torch','hardcore_torches:burnt_torch','valhelsia_structures:doused_torch'];
let LIGHTER_ITEMS = ['minecraft:flint_and_steel'];

function arrayContains(thing, array) {
    for (var a of array) {
      if (a == thing) return true;
   }
   return false;
};

global.torchLight = function(itemToTest, event, player) {
	const mainHand = itemToTest;
	const mainHandId = mainHand.id.toString();
	const offHand = player.getOffHandItem();
	const offHandId = offHand.id.toString();
	const mainCount = mainHand.count;
	const litTorch = Item.of(LIT_TORCH_ITEM, mainCount);
	
    if (arrayContains(offHandId, LIGHTER_ITEMS) && arrayContains(mainHandId, UNLIT_TORCH_ITEMS)) {
		player.setMainHandItem(litTorch);
		event.server.runCommandSilent(`playsound minecraft:item.flintandsteel.use player @a ${player.x} ${player.y} ${player.z} 1`);
		event.server.runCommandSilent(`playsound minecraft:block.fire.ambient player @a ${player.x} ${player.y} ${player.z} 1`);
		event.player.damageEquipment(EquipmentSlot.OFFHAND, mainCount);
	}
};

// event listeners

onEvent("item.right_click", event => {
    global.torchLight(event.item, event, event.player);
});

onEvent("block.right_click", event => {
    const { block, hand, item, world, player, server } = event;
    const blockXYZ = block.x+' '+block.y+' '+block.z

	if (hand.name() != 'MAIN_HAND') return;
    if (!arrayContains(item, LIGHTER_ITEMS)) return;
	
    if(arrayContains(block, UNLIT_TORCH_ITEMS)) {
        block.set(LIT_TORCH_ITEM);
		event.server.runCommandSilent(`playsound minecraft:item.flintandsteel.use player @a ${player.x} ${player.y} ${player.z} 1`);
		event.server.runCommandSilent(`playsound minecraft:block.fire.ambient player @a ${player.x} ${player.y} ${player.z} 1`);
        event.player.damageEquipment(EquipmentSlot.OFFHAND, 1);
		event.cancel();
    }
	
	if(arrayContains(block, UNLIT_TORCH_ITEMS_WALL)) {
        block.set(LIT_TORCH_ITEM_WALL, block.properties);
		event.server.runCommandSilent(`playsound minecraft:item.flintandsteel.use player @a ${player.x} ${player.y} ${player.z} 1`);
		event.server.runCommandSilent(`playsound minecraft:block.fire.ambient player @a ${player.x} ${player.y} ${player.z} 1`);
        event.player.damageEquipment(EquipmentSlot.OFFHAND, 1);
		event.cancel();
    }
});