package dangerzone.gui;
/*
 * This code is copyright Richard H. Clark, TheyCallMeDanger, OreSpawn, 2015-2020.
 * You may use this code for reference for modding the DangerZone game program,
 * and are perfectly welcome to cut'n'paste portions for your mod as well.
 * DO NOT USE THIS CODE FOR ANY PURPOSE OTHER THAN MODDING FOR THE DANGERZONE GAME.
 * DO NOT REDISTRIBUTE THIS CODE. 
 * 
 * This copyright remains in effect until January 1st, 2021. 
 * At that time, this code becomes public domain.
 * 
 * WARNING: There are bugs. Big bugs. Little bugs. Every size in-between bugs.
 * This code is NOT suitable for use in anything other than this particular game. 
 * NO GUARANTEES of any sort are given, either express or implied, and Richard H. Clark, 
 * TheyCallMeDanger, OreSpawn are not responsible for any damages, direct, indirect, or otherwise. 
 * You should have made backups. It's your own fault for not making them.
 * 
 * NO ATTEMPT AT SECURITY IS MADE. This code is USE AT YOUR OWN RISK.
 * Regardless of what you may think, the reality is, that the moment you 
 * connected your computer to the Internet, Uncle Sam, among many others, hacked it.
 * DO NOT KEEP VALUABLE INFORMATION ON INTERNET-CONNECTED COMPUTERS.
 * Or your phone...
 * 
 */


import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
import org.newdawn.slick.opengl.Texture;


import dangerzone.Crafting;
import dangerzone.DangerZone;
import dangerzone.InventoryContainer;
import dangerzone.Recipe;
import dangerzone.TextureMapper;
import dangerzone.Utils;
import dangerzone.blocks.Blocks;
import dangerzone.items.Item;
import dangerzone.items.ItemArmor;
import dangerzone.items.Items;




public class PlayerCraftingGUI extends GuiInterface {
	
	List<ButtonHandler> buttons; //more like inventory squares, really, but they do nicely as buttons
	List<MyCraftingHandler> crafting_buttons;
	List<MyCraftingHandler> spread_buttons; //list of buttons that player is trying to spread items/blocks over.
	int spread_iid = 0;
	int spread_bid = 0;
	int last_spread = -1;
	public Texture invtx = null;
	public Texture hottx = null;
	public Texture buttontexture = null;
	public Texture deletetexture = null;
	public Texture tosstexture = null;
	public Texture craft1texture = null;
	public Texture craft9texture = null;
	
	public InventoryContainer crafter[]; 
	public InventoryContainer crafted;
	public boolean shifted = false;
	public Texture helmettexture = null;
	public Texture leggingstexture = null;
	public Texture chestplatetexture = null;
	public Texture bootstexture = null;


	
	private class MyButtonHandler extends ButtonHandler {
		
		public int ih; //inventory or hotbar
		public int index; //index into above
		
		MyButtonHandler(int xpos, int ypos, int bxsize, int bysize, Texture tx, String ot, int i, int j){
			super(xpos, ypos, bxsize, bysize, tx, ot);
			ih = i;
			index = j;
		}
		
		MyButtonHandler(int xpos, int ypos, int bxsize, int bysize, InventoryContainer ic, int i, int j){
			super(xpos, ypos, bxsize, bysize, ic);
			ih = i;
			index = j;
		}
		
		public void leftclickhandler(){
			//System.out.printf("Left in %d,  %d\n", ih, index);
			if(ih == 9 || ih == 10 || ih == 11 || ih == 12){
				if(mousebite == null){
					//pick something UP
					mousebite = DangerZone.player.getArmor(index);
					DangerZone.player.setArmor(index, null);
				}else{
					//Try to add armor from mousebite
					InventoryContainer ic;	
					Item it;
					ItemArmor ia;
					it = Items.getItem(mousebite.iid);
					if(it == null)return;
					if(!(it instanceof ItemArmor))return;
					ia = (ItemArmor)it;
					if(ia.armortype != index)return;
					
					ic = DangerZone.player.getArmor(index);				
					DangerZone.player.setArmor(index, mousebite);						
					mousebite = ic;
				}
				if(shifted)mousebiteToInventory();
				return;
			}
			
			if(ih == 6){ //delete!
				mousebite = null;
				return;
			}
			
			if(ih < 0 || index < 0){
				if(mousebite != null){
					Utils.spitInventoryOut(mousebite);
					mousebite = null;
				}
				return;
			}
			if(mousebite == null){
				//pick something UP
				if(ih == 1){
					mousebite = DangerZone.player.getInventory(index);
					DangerZone.player.setInventory(index, null);
				}else{
					mousebite = DangerZone.player.getHotbar(index);
					DangerZone.player.setHotbar(index, null);
				}
			}else{
				//Try to add to existing from mousebite
				InventoryContainer ic;
				if(ih == 1){
					ic = DangerZone.player.getInventory(index);
				}else{
					ic = DangerZone.player.getHotbar(index);
				}
				if(ic != null){
					if(mousebite.bid == ic.bid && mousebite.iid == ic.iid){
						int mx = ic.getMaxStack() - ic.count;
						if(mx > 0){ //room for more?
							if(mx >= mousebite.count){
								ic.count += mousebite.count;
								mousebite = null;
							}else{
								mousebite.count -= mx;
								ic.count += mx;
							}
							if(ih == 1){
								DangerZone.player.setInventory(index, ic);
							}else{
								DangerZone.player.setHotbar(index, ic);
							}
						}
					}else{
						//NOT equal. Swap!
						if(ih == 1){
							DangerZone.player.setInventory(index, mousebite);
						}else{
							DangerZone.player.setHotbar(index, mousebite);
						}
						mousebite = ic;
					}
				}else{
					if(ih == 1){
						DangerZone.player.setInventory(index, mousebite);
					}else{
						DangerZone.player.setHotbar(index, mousebite);
					}
					mousebite = null;
				}
			}
		}
		public void rightclickhandler(){
			//System.out.printf("Right in %d,  %d\n", ih, index);
			//try picking up half
			if(mousebite == null){
				if(ih < 0 || ih > 1){
					return;
				}
				InventoryContainer ic;
				int mx = 0;
				if(ih == 1){
					ic = DangerZone.player.getInventory(index);
				}else{
					ic = DangerZone.player.getHotbar(index);
				}
				if(ic != null){
					mx = ic.count/2;
					if(mx == 0){
						mousebite = ic;
						if(ih == 1){
							DangerZone.player.setInventory(index, null);
						}else{
							DangerZone.player.setHotbar(index, null);
						}
					}else{
						mousebite = new InventoryContainer();
						mousebite.bid = ic.bid;
						mousebite.iid = ic.iid;
						mousebite.count = mx;
						ic.count -= mx;
						if(ih == 1){
							DangerZone.player.setInventory(index, ic);
						}else{
							DangerZone.player.setHotbar(index, ic);
						}
					}
				}
			}
		}
	}
	
	private class MyCraftingHandler extends ButtonHandler {
		
		public int ih; //crafter or crafted
		public int index; //index into above
		
		MyCraftingHandler(int xpos, int ypos, int bxsize, int bysize, Texture tx, String ot, int i, int j){
			super(xpos, ypos, bxsize, bysize, tx, ot);
			ih = i;
			index = j;
		}
		
		MyCraftingHandler(int xpos, int ypos, int bxsize, int bysize, InventoryContainer ic, int i, int j){
			super(xpos, ypos, bxsize, bysize, ic);
			ih = i;
			index = j;
		}
		
		public void leftclickhandler(){
			//System.out.printf("Left in %d,  %d\n", ih, index);
			if(mousebite == null){
				//pick something UP
				if(ih == 1){					
					mousebite = crafted;
					crafted = null;
					if(mousebite != null){
						for(int i=0;i<crafter.length;i++){
							if(crafter[i]!=null){
								if(crafter[i].iid == Items.bucketwater.itemID){
									crafter[i].iid = Items.bucket.itemID;
								}else{
									crafter[i].count--;
									if(crafter[i].count <= 0){
										crafter[i] = null;
									}
								}
							}
						}
					}
					return;
				}else{
					//if(K_isKeyDown(Keyboard.KEY_LSHIFT) || K_isKeyDown(Keyboard.KEY_RSHIFT)){
						//try to put it straight into inventory!
						
						
					//}else{
						mousebite = crafter[index];
						crafter[index] = null;	
					//}
				}
			}else{
				//Try to add to existing from mousebite
				InventoryContainer ic;
				if(ih == 1){
					if(crafted != null){
						if(crafted.bid == mousebite.bid && crafted.iid == mousebite.iid){
							if(mousebite.count + crafted.count <= mousebite.getMaxStack()){
								mousebite.count += crafted.count;
								for(int i=0;i<crafter.length;i++){
									if(crafter[i]!=null){
										if(crafter[i].iid == Items.bucketwater.itemID){
											crafter[i].iid = Items.bucket.itemID;
										}else{
											crafter[i].count--;
											if(crafter[i].count <= 0){
												crafter[i] = null;
											}
										}
									}
								}
							}
						}
					}
					return;
				}
				ic = crafter[index];
				
				if(ic != null){
					if(mousebite.bid == ic.bid && mousebite.iid == ic.iid){
						int mx = ic.getMaxStack() - ic.count;
						if(mx > 0){ //room for more?
							if(mx >= mousebite.count){
								ic.count += mousebite.count;
								mousebite = null;
							}else{
								mousebite.count -= mx;
								ic.count += mx;
							}
							crafter[index] = ic;							
						}
					}else{
						//NOT equal. Swap!
						crafter[index] = mousebite;
						mousebite = ic;
					}
				}else{					
					crafter[index] = mousebite;			
					mousebite = null;
				}
			}
			if(shifted)mousebiteToInventory();
			
		}
		public void rightclickhandler(){
			//System.out.printf("Right in %d,  %d\n", ih, index);
			//try picking up half
			if(mousebite == null && ih == 0){				
				InventoryContainer ic;
				int mx = 0;				
				ic = crafter[index];				
				if(ic != null){
					mx = ic.count/2;
					if(mx == 0){
						mousebite = ic;
						crafter[index] = null;
					}else{
						mousebite = new InventoryContainer();
						mousebite.bid = ic.bid;
						mousebite.iid = ic.iid;
						mousebite.count = mx;
						ic.count -= mx;
						crafter[index] = ic;
					}
				}
			}
		}
	}
	
	public PlayerCraftingGUI(){
		super();
		buttons = null;
		spread_buttons = null;
		mousebite = null;
		crafted = null;
		crafter = new InventoryContainer[9];

		invtx = TextureMapper.getTexture("res/menus/playerinventory.png");
		hottx = TextureMapper.getTexture("res/menus/playerhotbar.png");
		buttontexture = TextureMapper.getTexture("res/menus/"+"button.png");
		deletetexture = TextureMapper.getTexture("res/menus/"+"deletebutton.png");
		tosstexture = TextureMapper.getTexture("res/menus/"+"tossbutton.png");
		craft1texture = TextureMapper.getTexture("res/menus/"+"craft1.png");
		craft9texture = TextureMapper.getTexture("res/menus/"+"craft9.png");
		helmettexture = TextureMapper.getTexture("res/menus/"+"invhelmet.png");
		chestplatetexture = TextureMapper.getTexture("res/menus/"+"invchestplate.png");
		leggingstexture = TextureMapper.getTexture("res/menus/"+"invleggings.png");
		bootstexture = TextureMapper.getTexture("res/menus/"+"invboots.png");

	}

	/*
	 * This is the callback from main to process the GUI.
	 * 
	 */
	public void process(){
		int i, row, col;
		int startx, starty;
		int cellsize = 50;
		int clickx, clicky;
		ButtonHandler mb = null;
		ButtonHandler fb = null;
		Texture tx;
		String s = null;
		int mod = 10;
		float scalex = DangerZone.screen_width/1350f;
		float scaley = DangerZone.screen_height/700f;
		startx = 100;
		starty = 600;
		if(scalex < scaley)scaley = scalex;
		if(scaley < scalex)scalex = scaley;
		
		if(K_isKeyDown(Keyboard.KEY_LSHIFT) || K_isKeyDown(Keyboard.KEY_RSHIFT)){
			shifted = true;
		}else{
			shifted = false;
		}
		
		//OpenGL has some quirks...
		drawRectangleWithTexture(invtx, (startx-5)*scalex, (starty-205)*scaley, 500*scalex, 250*scaley);
		
		//Build the button list... yeah... i know... would be nice to not recreate it every time...
		//but they do have a tendency to change dynamically, so we don't...
		buttons = new ArrayList<ButtonHandler>();
		crafting_buttons = new ArrayList<MyCraftingHandler>();
		for(i=0;i<50;i++){
			row = i/mod;
			col = i%mod;		
			buttons.add(new MyButtonHandler((int)((startx+cellsize*col)*scalex), (int)((starty-row*cellsize)*scaley), (int)(40*scalex), (int)(40*scaley), DangerZone.player.getInventory(i), 1, i)); //1 = inventory
		}
		
		//add hotbar buttons...
		starty -= 300;
		drawRectangleWithTexture(hottx, (startx-5)*scalex, (starty-5)*scaley, 500*scalex, 50*scaley);
		for(i=0;i<10;i++){
			row = 0;
			col = i;
			buttons.add(new MyButtonHandler((int)((startx+cellsize*col)*scalex), (int)((starty-row*cellsize)*scaley), (int)(40*scalex), (int)(40*scaley), DangerZone.player.getHotbar(i), 0, i)); //0 = hotbar
		}
				
		//add armor buttons!
		starty = 200;
		drawRectangleWithTexture(helmettexture, (startx-5)*scalex, (starty-5)*scaley, 50*scalex, 50*scaley);
		buttons.add(new MyButtonHandler((int)((startx)*scalex), (int)((starty)*scaley), (int)(40*scalex), (int)(40*scaley), DangerZone.player.getArmor(0), 9, 0));

		drawRectangleWithTexture(chestplatetexture, (startx+45)*scalex, (starty-5)*scaley, 50*scalex, 50*scaley);
		buttons.add(new MyButtonHandler((int)((startx+50)*scalex), (int)((starty)*scaley), (int)(40*scalex), (int)(40*scaley), DangerZone.player.getArmor(1), 10, 1));

		drawRectangleWithTexture(leggingstexture, (startx+95)*scalex, (starty-5)*scaley, 50*scalex, 50*scaley);
		buttons.add(new MyButtonHandler((int)((startx+100)*scalex), (int)((starty)*scaley), (int)(40*scalex), (int)(40*scaley), DangerZone.player.getArmor(2), 11, 2));

		drawRectangleWithTexture(bootstexture, (startx+145)*scalex, (starty-5)*scaley, 50*scalex, 50*scaley);
		buttons.add(new MyButtonHandler((int)((startx+150)*scalex), (int)((starty)*scaley), (int)(40*scalex), (int)(40*scaley), DangerZone.player.getArmor(3), 12, 3));	
		
		//Normal 9-square crafting!
		starty = 600;
		startx = 775;
		drawRectangleWithTexture(craft9texture, (startx-2)*scalex, (starty-165)*scaley, 150*scalex, 150*scaley);
		drawRectangleWithTexture(craft1texture, (startx+180)*scalex, (starty-70)*scaley, 50*scalex, 50*scaley);

		//Now go back and fill in buttons
		starty = 600;

		for(i=0;i<crafter.length;i++){
			row = i/3;
			col = i%3;
			crafting_buttons.add(new MyCraftingHandler((int)((startx+cellsize*col+5)*scalex), (int)((starty-row*cellsize-59)*scaley), (int)(40*scalex), (int)(40*scaley), crafter[i], 0, i)); //0 = crafter
		}
		
		crafted = null;
		Recipe r = Crafting.find(crafter[0]==null?null:crafter[0].getUniqueName(), crafter[1]==null?null:crafter[1].getUniqueName(), crafter[2]==null?null:crafter[2].getUniqueName(),
				crafter[3]==null?null:crafter[3].getUniqueName(), crafter[4]==null?null:crafter[4].getUniqueName(), crafter[5]==null?null:crafter[5].getUniqueName(),
						crafter[6]==null?null:crafter[6].getUniqueName(), crafter[7]==null?null:crafter[7].getUniqueName(), crafter[8]==null?null:crafter[8].getUniqueName());
		if(r != null){
			crafted = new InventoryContainer(r.outname, r.out_count);
		}
		
		
		buttons.add(new MyCraftingHandler((int)((startx+185)*scalex), (int)((starty-65)*scaley), (int)(40*scalex), (int)(40*scaley), crafted, 1, 0)); //1 = crafted
	
		buttons.add(new MyButtonHandler((int)(650*scalex), (int)(500*scaley), (int)(50*scalex), (int)(50*scaley), deletetexture, null, 6, 0)); //delete button
		buttons.add(new MyButtonHandler((int)(650*scalex), (int)(560*scaley), (int)(50*scalex), (int)(50*scaley), tosstexture, null, -1, -1)); //toss button
		
		//catch-all!
		//buttons.add(new MyButtonHandler(0, 0, DangerZone.screen_width, DangerZone.screen_height, null, null, -1, -1));
		
		
		//Now draw them!
		Iterator<ButtonHandler> bb = buttons.iterator();
		while(bb.hasNext()){
			bb.next().draw();
		}
		Iterator<MyCraftingHandler> bc = crafting_buttons.iterator();
		while(bc.hasNext()){
			bc.next().draw();
		}
		
		//Draw the things under the mouse
		if(mousebite != null){			
			tx = mousebite.getTexture();
			s = null;
			if(mousebite.count > 1){
				s = String.format("%d", mousebite.count);
			}
			if(tx != null){
				GL11.glColor3f(1,1,1);
				drawRectangleWithTexture(tx, M_getX()-16, M_getY()-16, 32, 32);
			}
			if(s != null && !s.equals("")){
				textAt( M_getX()-16, M_getY()-16, s);
				GL11.glColor3f(1,1,1); //because text messes this up!
			}
		}
		

		
		
		//Check for mouse events on our button list!
		while(M_next()){
			clickx = M_getEventX();
			clicky = M_getEventY();
			if(!M_getEventButtonState()){ //Mouse button UP!
				if(M_getEventButton() >= 0){ //clicked!				
					//Find which "button" they clicked on
					bc = crafting_buttons.iterator();
					fb = null;
					while(bc.hasNext()){
						mb = bc.next();
						if(clickx >= mb.x && clickx <= mb.x+mb.xsize){
							if(clicky >= mb.y && clicky <= mb.y+mb.ysize){
								fb = mb;
								break;
							}
						}
					}
					// 0 = left, 1 = right, 2 = middle
					if(M_getEventButton() == 0){
						//if(fb != null && (spread_buttons == null || spread_buttons.size() == 1)){
						//	fb.leftclickhandler();
						//}
						spread_buttons = null;
						last_spread = -1;
					}
					if(M_getEventButton() == 1){
						spread_buttons = null;
						last_spread = -1;
					}
				}
			}else{ //mouse button down
				if(M_getEventButton() >= 0){ //clicked!				
					//Find which "button" they clicked on
					//System.out.printf("down\n");
					bb = buttons.iterator();
					fb = null;
					while(bb.hasNext()){
						mb = bb.next();
						if(clickx >= mb.x && clickx <= mb.x+mb.xsize){
							if(clicky >= mb.y && clicky <= mb.y+mb.ysize){
								fb = mb;
								break;
							}
						}
					}
					// 0 = left, 1 = right, 2 = middle
					if(M_getEventButton() == 0){												
						if(fb != null){
							fb.leftclickhandler();
							spread_buttons = null;
						}
						last_spread = -1;
					}
					if(M_getEventButton() == 1){
						if(fb != null)fb.rightclickhandler();
						spread_buttons = null;
						last_spread = -1;
					}
					
/* crafting buttons */					
										
					bc = crafting_buttons.iterator();
					fb = null;
					while(bc.hasNext()){
						mb = bc.next();
						if(clickx >= mb.x && clickx <= mb.x+mb.xsize){
							if(clicky >= mb.y && clicky <= mb.y+mb.ysize){
								fb = mb;
								break;
							}
						}
					}
					// 0 = left, 1 = right, 2 = middle
					if(M_getEventButton() == 0){						
						if(fb != null && (fb.ic != null || mousebite != null )){
							if((mousebite != null && fb.ic == null) ||
							  (mousebite != null && fb.ic != null && mousebite.bid == fb.ic.bid && mousebite.iid == fb.ic.iid)){
								if(spread_buttons == null){
									spread_buttons = new ArrayList<MyCraftingHandler>();
									if(mousebite != null){
										spread_iid = mousebite.iid;
										spread_bid = mousebite.bid;
									}else{
										spread_iid = fb.ic.iid;
										spread_bid = fb.ic.bid;
									}
								}
							}else{
								fb.leftclickhandler();
							}
						}else{
							if(fb != null){
								fb.leftclickhandler();
							}
						}
					}
					if(M_getEventButton() == 1){
						if(fb != null){
							//fb.rightclickhandler();
							MyCraftingHandler ch = (MyCraftingHandler)fb;
							last_spread = ch.index;
							if(ch.ic == null && mousebite != null){
								 crafter[ch.index] = new InventoryContainer(mousebite.bid, mousebite.iid, 1, 0);
								 mousebite.count--;
								 if(mousebite.count <= 0)mousebite = null;								
							}else if(ch.ic != null && mousebite != null && ch.ic.bid == mousebite.bid && ch.ic.iid == mousebite.iid){								
								if(mousebite.bid != 0){
									if(Blocks.getMaxStack(mousebite.bid) > ch.ic.count){
										ch.ic.count++;
										 mousebite.count--;
										 if(mousebite.count <= 0)mousebite = null;		
									}
								}
								if(mousebite != null && mousebite.iid != 0){
									if(Items.getMaxStack(mousebite.iid) > ch.ic.count){
										ch.ic.count++;	
										 mousebite.count--;
										 if(mousebite.count <= 0)mousebite = null;		
									}
								}			
							}else{
								fb.rightclickhandler();
							}
						}
						spread_buttons = null;
					}
				}
				
			}
		}
		
		//show some descriptive text and handle spreading!
		int cx, cy;
		cx = M_getX();
		cy = M_getY();
		bb = buttons.iterator();
		fb = null;
		while(bb.hasNext()){
			mb = bb.next();
			if(cx >= mb.x && cx <= mb.x+mb.xsize){
				if(cy >= mb.y && cy <= mb.y+mb.ysize){
					InventoryContainer ic = mb.ic;
					if(ic != null){
						String hotstring = null;
						String[] hss = null;
						if(ic.bid != 0){
							hotstring = Blocks.getUniqueName(ic.bid);
						}
						if(ic.iid != 0){
							hotstring = Items.getUniqueName(ic.iid);
						}
						if(hotstring != null){
							hss = hotstring.split(":");
							if(hss.length >= 2){
								DangerZone.hotmessagestring = hss[1];
								DangerZone.hotmessagetimer = 10;
							}
						}
					}
				}
			}
		}
		
		cx = M_getX();
		cy = M_getY();
		bc = crafting_buttons.iterator();
		fb = null;
		while(bc.hasNext()){
			mb = bc.next();
			if(cx >= mb.x && cx <= mb.x+mb.xsize){
				if(cy >= mb.y && cy <= mb.y+mb.ysize){
					InventoryContainer ic = mb.ic;
					if(ic != null){
						String hotstring = null;
						String[] hss = null;
						if(ic.bid != 0){
							hotstring = Blocks.getUniqueName(ic.bid);
						}
						if(ic.iid != 0){
							hotstring = Items.getUniqueName(ic.iid);
						}
						if(hotstring != null){
							hss = hotstring.split(":");
							if(hss.length >= 2){
								DangerZone.hotmessagestring = hss[1];
								DangerZone.hotmessagetimer = 10;
							}
						}
					}
					if(spread_buttons != null && !isOnSpreadList(spread_buttons, mb)){
						if(mb.ic == null || (mb.ic != null && mb.ic.bid == spread_bid && mb.ic.iid == spread_iid)){
							spread_buttons.add((MyCraftingHandler) mb);
							//System.out.printf("added %d,  %d\n", mb.x, mb.y);
						}						
					}
					MyCraftingHandler ch = (MyCraftingHandler)mb;
					if(last_spread >= 0 && last_spread != ch.index){
						last_spread = ch.index;						
						if(ch.ic == null && mousebite != null){
							 crafter[ch.index] = new InventoryContainer(mousebite.bid, mousebite.iid, 1, 0);
							 mousebite.count--;
							 if(mousebite.count <= 0)mousebite = null;								
						}else if(ch.ic != null && mousebite != null && ch.ic.bid == mousebite.bid && ch.ic.iid == mousebite.iid){								
							if(mousebite.bid != 0){
								if(Blocks.getMaxStack(mousebite.bid) > ch.ic.count){
									ch.ic.count++;
									 mousebite.count--;
									 if(mousebite.count <= 0)mousebite = null;		
								}
							}
							if(mousebite != null && mousebite.iid != 0){
								if(Items.getMaxStack(mousebite.iid) > ch.ic.count){
									ch.ic.count++;	
									 mousebite.count--;
									 if(mousebite.count <= 0)mousebite = null;		
								}
							}			
						}
					}					
				}
			}
		}
		
		//handle spread buttons list, redistribute if necessary
		if(spread_buttons != null){
			if(!spread_buttons.isEmpty()){
				int totalcount = 0;

				//get a grand total
				bc = spread_buttons.iterator();
				if(mousebite != null){
					totalcount = mousebite.count;
					mousebite = null;
				}
				while(bc.hasNext()){
					fb = bc.next();
					if(fb != null){
						if(fb.ic != null)totalcount += fb.ic.count;
					}
				}
				
				//clear
				bc = spread_buttons.iterator();
				while(bc.hasNext()){
					fb = bc.next();
					if(fb.ic != null){
						fb.ic = null;
					}
				}
				
				//redistribute
				boolean roomleft = true;
				while(totalcount > 0 && roomleft){
					bc = spread_buttons.iterator();
					roomleft = false;
					while(bc.hasNext() && totalcount > 0){
						fb = bc.next();
						if(fb.ic == null){
							fb.ic = new InventoryContainer(spread_bid, spread_iid, 1, 0);
							totalcount--;
							roomleft = true;
						}else{
							if(spread_bid != 0){
								if(Blocks.getMaxStack(spread_bid) > fb.ic.count){
									fb.ic.count++;
									fb.ic.bid = spread_bid;
									fb.ic.iid = spread_iid;
									totalcount--;
									roomleft = true;
								}
							}
							if(spread_iid != 0){
								if(Items.getMaxStack(spread_iid) > fb.ic.count){
									fb.ic.count++;
									fb.ic.bid = spread_bid;
									fb.ic.iid = spread_iid;
									totalcount--;
									roomleft = true;
								}
							}							
						}
					}
				}
				
				//and finally, transfer the buttons back to the crafter...
				bc = spread_buttons.iterator();
				while(bc.hasNext()){
					fb = bc.next();			
					MyCraftingHandler ch = (MyCraftingHandler)fb;
					crafter[ch.index] = fb.ic;					
				}
				
				if(totalcount > 0){
					mousebite = new InventoryContainer(spread_bid, spread_iid, totalcount, 0);
				}
				
			}
		}
		
		//Check for exit
		while(K_next()){
			if (K_getEventKey() == Keyboard.KEY_E && K_isKeyDown(Keyboard.KEY_E)){
				ImAllDone();
				return;
			}
			if (K_getEventKey() == Keyboard.KEY_ESCAPE && K_isKeyDown(Keyboard.KEY_ESCAPE)){
				ImAllDone();
				return;
			}
		}
		
	}
	
	public boolean isOnSpreadList(List <MyCraftingHandler> lst, ButtonHandler b){
		if(lst == null)return false;
		if(lst.isEmpty())return false;
		
		Iterator<MyCraftingHandler> bb = lst.iterator();
		ButtonHandler bt;
		while(bb.hasNext()){
			bt = bb.next();
			if(b.x != bt.x)continue;
			if(b.y != bt.y)continue;
			if(b.xsize != bt.xsize)continue;
			if(b.ysize != bt.ysize)continue;
			return true;
		}
		return false;
	}
	
	public void ImAllDone(){

		//refresh hotbar and inventory contents!!!!!
		for(int i=0;i<10;i++){			
			DangerZone.player.setHotbarChanged(i);
		}
		for(int i=0;i<50;i++){
			DangerZone.player.setInventoryChanged(i);
		}
		for(int i=0;i<4;i++){
			DangerZone.player.setArmorChanged(i);
		}
		
		
		Utils.spitInventoryOut(mousebite);
		for(int i=0;i<crafter.length;i++){
			Utils.spitInventoryOut(crafter[i]);
		}
		
		crafted = null;
		mousebite = null;
		crafted = null;
		crafter = new InventoryContainer[9];
		spread_buttons = null;
		buttons = null;
		spread_bid = spread_iid = 0;
		last_spread = -1;
		
		super.ImAllDone();
	}

}
