package cz.cuni.amis.pogamut.ut2004.communication.itemtranslator;

import java.lang.reflect.Field;

/**
 * A parent of all item descriptors.
 * 
 * Contains attributes common for all descriptors plus some common functions.
 * 
 * @author Ondrej, knight
 * 
 */
public abstract class ItemDescriptor {
    
	private int amount;
        
        private String inventoryType;
        
        private String pickupType;
        
        private String itemCategory; 
               
	public int getAmount() {
		return amount;
	}

        public String getInventoryType()
        {
            return inventoryType;
        }
        
        public String getPickupType()
        {
            return pickupType;
        }
        
        public String getItemCategory()
        {
            return itemCategory;
        }        

	/**
	 * Converts a fully qualified field name (e.g. private boolean cz.cuni.amis.MyClass.myBoolean)
	 * to a field name (e.g. myBoolean).
	 * 
	 * @param string - complete identifier of a field in a class
	 * @return name of a field
	 */
	protected String fieldToName(String string) {
		String result = string.substring(string.lastIndexOf(".") + 1);
		return firstCharToUpperCase(result);
	}
	
	protected String firstCharToUpperCase(String input) {
		return input.substring(0,1).toUpperCase() + input.substring(1);
	}

	/**
	 * This method does the mapping from a map of attributes contained it ITCMsg and the attributes of the descriptor.
	 * 
	 * NOTE: names of the attributes must be equal to the keys of the HashMap contained in ITCMsg.
	 * 
	 * @param configMsg
	 */
	protected void doReflexion(ITCMsg configMsg, Class<? extends ItemDescriptor> clazz) {
		Field[] fields = clazz.getDeclaredFields();
		Field field;
		for (int i = 0; i < fields.length; ++i) {
			field = fields[i];
			String key = fieldToName(field.toString());
			if (configMsg.contains(key)) {
				field.setAccessible(true);
				try {
					field.set(this, configMsg.get(key));
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				}
				field.setAccessible(false);
			}
		}
	}
	
	public abstract String toString();

}
