package com.zivilon.cinder_loe.carriage.gui;

import lotr.common.LOTRMod;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;

public class CarriageCoinUtil {
    public static boolean removeCoinsAndGiveChange(EntityPlayer player, int cost) {
        int total = 0;
        for (ItemStack stack : player.inventory.mainInventory) {
            if (stack != null && stack.getItem() == LOTRMod.silverCoin) {
                total += getCoinValue(stack) * stack.stackSize;
            }
        }
        if (total < cost) {
            return false;
        }
        // clear all silver coins
        for (int i = 0; i < player.inventory.mainInventory.length; i++) {
            ItemStack stack = player.inventory.mainInventory[i];
            if (stack != null && stack.getItem() == LOTRMod.silverCoin) {
                player.inventory.setInventorySlotContents(i, null);
            }
        }
        int change = total - cost;
        // give change: 100$,10$,1$ in correct metadata order
        int[] metas = {2, 1, 0};
        for (int meta : metas) {
            int value = meta == 2 ? 100 : meta == 1 ? 10 : 1;
            int count = change / value;
            change %= value;
            while (count > 0) {
                int size = Math.min(count, LOTRMod.silverCoin.getItemStackLimit());
                ItemStack out = new ItemStack(LOTRMod.silverCoin, size, meta);
                player.inventory.addItemStackToInventory(out);
                count -= size;
            }
        }
        player.inventory.markDirty();
        return true;
    }

    private static int getCoinValue(ItemStack stack) {
        int meta = stack.getItemDamage();
        return meta == 2 ? 100 : meta == 1 ? 10 : 1;
    }
}
