let ID_BOOK = "minecraft:enchanted_book";
let NBT_STRING = '{StoredEnchantments:[{id:"tombstone:soulbound",lvl:1s}]}';
let ENCHANT_BLACKLIST = [
    "sophisticatedbackpacks:backpack",
    "sophisticatedbackpacks:gold_backpack",
    "sophisticatedbackpacks:iron_backpack",
    "sophisticatedbackpacks:diamond_backpack"
];

// foo bar

const playerHasSouldbound = (item, player) => {
    let index = player.inventory.find(Item.of(item).ignoreNBT());
    if (index != -1) {
        let item = player.inventory.get(index);
        let nbtData = item.getNbt();
        return index != -1 && nbtData === NBT_STRING;
    }
    return false;
};

const soulboundItem = (item, player) => {
    let index = player.inventory.find(Item.of(item).ignoreNBT());
    if (index != -1) {
        let item = player.inventory.get(index);
        return item;
    }
    return null;
}

const isSoulboundBook = (item) => {
    let nbtData = item.getNbt();
    return nbtData === NBT_STRING;
};

const soulboundActive = (player) => {
    return player.nbt.soulbound == 1
}

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

global.enchantCheck = function(itemToTest, event, player) {
    if (itemToTest) {
        if (isSoulboundBook(itemToTest)) {
            if (soulboundActive(player)) {
                player.nbt.soulbound = 0;
                player.tell("§7Зачарование отменено.");
            } else {
				player.nbt.soulbound = 1;
				player.tell("§7Возьмите в руку предмет и нажмите ПКМ, чтобы зачаровать его.");
            }
        } else {
            if (soulboundActive(player)) {
                let sItem = soulboundItem(ID_BOOK, player);
				if (arrayContains(itemToTest, ENCHANT_BLACKLIST)) {
					player.nbt.soulbound = 0;
					player.tell("§cВы не можете зачаровать этот предмет на связывание души. Зачарование отменено");
					return;
				}
                if (playerHasSouldbound(ID_BOOK, player) && sItem != null) {
                    player.nbt.soulbound = 0;
                    sItem.count = sItem.count - 1;
                    player.tell("§aЗачарование успешно!");
					event.server.runCommandSilent(`playsound block.enchantment_table.use player @a ${player.x} ${player.y} ${player.z} 1`);
                    event.player.server.runCommandSilent(`enchant ${event.player.id} tombstone:soulbound 1`);
                } else {
                    player.nbt.soulbound = 0;
                    player.tell("§eКнига с зачарованием не найдена. Зачарование отменено.");
                }
            }
        }
    }
};

// event listeners

onEvent("item.right_click", event => {
	if (event.hand == MAIN_HAND) {
		global.enchantCheck(event.item, event, event.player);
	}
});