/*
 *  Шансы дропа:
 *      1 тир: 50% выпадений
 *      2 тир: 30% 
 *      3 тир: 12%
 *      4 тир: 6%
 *      5 тир: 2%
*/

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

global.caseList = function(itemToTest, event, player, nameItem) {
    if (itemToTest) {
        var id = itemToTest.id.toString();

        var casesID = [];
        var cases = global.getCases();
        for(var i = 0; i < cases.length; i++)
        casesID[i] = 'kubejs:' + cases[i][0]
        
        if (relaxedContains(id, casesID)) {
			var item = global.random(global.getCaseContent(id.replace('kubejs:', '')))
			event.player.give(item)
			event.server.tell(text.green('§e'+player+` §aоткрыл §e${global.getNameCase(id)}§a и получил §ex${global.idItemToCountItem(item)} ${global.idItemToNameItem(item)}`))

            itemToTest.count--;
            event.cancel();
        }
    }
};

global.getNameCase = function(id) {
    var cases = global.getCases();
    for (var i = 0; i < cases.length; i++){
        if ('kubejs:' + cases[i][0] === id){
            return cases[i][1];
        }
    }
}

events.listen("item.right_click", function(event) {

    global.idItemToNameItem = function(idItem) {
        return item.of(idItem).name
    }

    global.idItemToCountItem = function(idItem) {
        return item.of(idItem).count
    }

    global.caseList(event.item, event, event.player);
});

// Рандомайзер предметов
global.random = function(items) {
    if(items[0].length != 0)
    var blue = items[0][Math.floor(Math.random()*items[0].length)];

    if(items[1].length != 0)
    var purple = items[1][Math.floor(Math.random()*items[1].length)];

    if(items[2].length != 0)
    var lightPurple = items[2][Math.floor(Math.random()*items[2].length)];

    if(items[3].length != 0)
    var red = items[3][Math.floor(Math.random()*items[3].length)];
    
    if(items[4].length != 0)
    var gold = items[4][Math.floor(Math.random()*items[4].length)];

    var rand = Math.random()*100;

    if (rand <= 55){
        return blue;
    } else if (rand <= 80) {
        if (items[1].length === 0){
            return blue;
        }
        return purple;
    } else if (rand <= 92) {
        if (items[2].length === 0){
            return blue;
        }
        return lightPurple;
    } else if (rand <= 98) {
        if (items[3].length === 0){
            return blue;
        }
        return red;
    } else {
        if (items[4].length === 0){
            return blue;
        }
        return gold;
    }
};