package csa.jmom.unit;

import javax.swing.JOptionPane;
import java.util.*;
public class  UnitDataPool
{
	public static final String DEFAULT_XML_NAME = new String("UnitData.xml");
	private String mFileName = DEFAULT_XML_NAME;
	private HashMap<String, UnitData> mUnitData = new HashMap<String, UnitData>();
	private HashMap<String, String> mKlassenMap = new HashMap<String, String>();
	public UnitDataPool(String name)
	{
		mFileName = name;
		init();
	}
	public UnitDataPool()
	{
		init();
	}
	public void setFilename(String n)
	{
		mFileName=n;
	}
	private boolean init()
	{
		try
		{
			return load();
		}
		catch (Throwable e)
		{
			JOptionPane.showMessageDialog(null, e.toString() ,"Load Error UnitData...",  JOptionPane.INFORMATION_MESSAGE);
			return false;
		}
	}
	public boolean load()
	{
		java.io.File f = new java.io.File(csa.Global.mBaseDir+mFileName);
		if (!f.exists()) return false;
		mUnitData = UnitData.getHashMapFromXML(mFileName);
		return true;
	}
	public void save()
	{
		UnitData.saveCollectionAsXML(mFileName, mUnitData.values());
		buildKlassenMap();
	}
	public void remove(UnitData st)
	{
		mUnitData.remove(st.mName);
	}
	public void put(UnitData st)
	{
		mUnitData.remove(st.mName);
		mUnitData.put(st.mName, st);
	}
	public void putAsNew(UnitData st)
	{
		mUnitData.put(st.mName, st);
	}
	public UnitData get(String key)
	{
		return mUnitData.get(key);
	}
	public HashMap<String, UnitData> getHashMap()
	{
		return mUnitData;
	}
	private void buildKlassenMap()
	{
		mKlassenMap = new HashMap<String, String>();
		Set entries = mUnitData.entrySet();
		Iterator it = entries.iterator();
		while (it.hasNext())
		{
			Map.Entry entry = (Map.Entry) it.next();
			UnitData value = (UnitData) entry.getValue();
			mKlassenMap.put(value.mClass, value.mClass);
		}
	}
	public HashMap<String, String> getKlassenHashMap()
	{
		buildKlassenMap();
		return mKlassenMap;
	}
	public HashMap<String, UnitData> getMapForKlasse(String klasse)
	{
		HashMap<String, UnitData> ret = new HashMap<String, UnitData>();
		Set entries = mUnitData.entrySet();
		Iterator it = entries.iterator();
		while (it.hasNext())
		{
			Map.Entry entry = (Map.Entry) it.next();
			UnitData value = (UnitData) entry.getValue();
			if (value.mClass.equalsIgnoreCase(klasse))
			{
				ret.put(value.mName, value);
			}
		}
		 return ret;
	}
}
