package info.jbcs.minecraft.chisel;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;

import net.minecraft.block.Block;

public class Carving {
	class CarvingGroup{
		public CarvingGroup(String n) {
			name=n;
		}

		String name;
		String className;
		String sound;
		
		ArrayList<CarvingVariation> variations=new ArrayList<CarvingVariation>();
	};
	
	HashMap<String,CarvingGroup> carvingGroupsByName=new HashMap<String,CarvingGroup>();
	HashMap<String,CarvingGroup> carvingGroupsByVariation=new HashMap<String,CarvingGroup>();

	public static Carving chisel=new Carving();
	
	String key(int blockId,int metadata){
		return blockId+"|"+metadata;
	}
	
	public boolean isVariationOfSameClass(int blockId1,int metadata1,int blockId2,int metadata2){
		CarvingGroup group1=carvingGroupsByVariation.get(key(blockId1,metadata1));
		if(group1==null) return false;
		
		CarvingGroup group2=carvingGroupsByVariation.get(key(blockId2,metadata2));
		if(group2==null) return false;
		
		if(group1==group2)
			return true;
		
		return group1.className.equals(group2.className) && ! group1.className.isEmpty();
	}
	
	public CarvingVariation[] getVariations(int blockId,int metadata){
		if(blockId==Block.stone.blockID) blockId=Block.stoneBrick.blockID;
		
		CarvingGroup group=carvingGroupsByVariation.get(key(blockId,metadata));
		if(group==null) return null;
		
		CarvingVariation[] res=group.variations.toArray(new CarvingVariation[group.variations.size()]);
		return res;
	}
	
	CarvingGroup getGroup(String name){
		CarvingGroup group=carvingGroupsByName.get(name);
		if(group==null){
			group=new CarvingGroup(name);
			group.className=name;
			carvingGroupsByName.put(name,group);
		}
		
		return group;
	}
	
	public CarvingVariation addVariation(String name,int blockId,int metadata,int order){
		CarvingGroup group=getGroup(name);
		
		CarvingGroup blockGroup=carvingGroupsByVariation.get(key(blockId,metadata));
		if(blockGroup!=null || blockGroup==group) return null;
		
		CarvingVariation variation=new CarvingVariation(blockId,metadata,order);
		group.variations.add(variation);
		Collections.sort(group.variations);
		carvingGroupsByVariation.put(key(blockId,metadata), group);
		
		return variation;
	}
	
	public void setGroupClass(String name,String className){
		CarvingGroup group=getGroup(name);
		
		group.className=className;
	}

	public void setVariationSound(String name, String sound) {
		CarvingGroup group=getGroup(name);
		group.sound=sound;
	}
	
	public String getVariationSound(int blockId,int metadata) {
		CarvingGroup blockGroup=carvingGroupsByVariation.get(key(blockId,metadata));
		if(blockGroup==null || blockGroup.sound==null) return "random.chisel";
		
		return blockGroup.sound;
	}
	
}

