package vermilion;

import java.util.ArrayList;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;

/**
 * A TreeMap wrapper for UsefulFileObjects, which is itself a UsefulFileObject.
 * This class wraps an (Integer, UsefulFileObject) Treemap, allowing storage of
 * objects with an index, which we use for storing pattern commands.
 */
public class UsefulFileObjectIntMap extends UsefulFileObject
{
    /**
     * The list of objects stored as part of this object.
     */
    public TreeMap<Integer, UsefulFileObject> arrayValue;

    /**
     * The serialisation type for this object is 'INTMAP'.
     */
    @Override
    public String getType() { return "INTMAP"; }

    /**
     * The current serialisation version for this object is 1.
     */
    @Override
    public int getVersion() { return 1; }

    /**
     * Creates a new empty integer map object.
     */
    public UsefulFileObjectIntMap()
    {
        arrayValue = new TreeMap<Integer, UsefulFileObject>();
    }

    /**
     * Loads the object from serialised form.
     */
    @Override
    public UsefulFileObject loadImpl(String str, int version)
    {
        if (version == 1)
        {
            UsefulFileObjectIntMap listVal = new UsefulFileObjectIntMap();

            ArrayList<String> subs = stringToList(str);

            for (String sub : subs)
            {
                try
                {
                    String[] entry = sub.split("\n");
                    listVal.put(Integer.parseInt(entry[0]), UsefulFileObject.load(entry[1]));
                }
                catch (Exception ex) {}
            }

            return listVal;
        }

        return null;
    }

    /**
     * Turns the object into serialised form.
     */
    @Override
    public String saveImpl()
    {
        ArrayList<String> list = new ArrayList<String>();

        Set<Entry<Integer, UsefulFileObject>> set = arrayValue.entrySet();

        for (Entry<Integer, UsefulFileObject> entry : set)
        {
            // TODO: Handle entry containing \n (by putting two entries).
            list.add(entry.getKey() + "\n" + entry.getValue().save());
        }

        return listToString(list);
    }

    /**
     * Provides mapped access to the map.
     */
    public void put(int i, UsefulFileObject o)
    {
        arrayValue.put(i, o);
    }

    /**
     * Provides mapped access to the map.
     */
    public UsefulFileObject get(int x)
    {
        return arrayValue.get(x);
    }

    /**
     * Provides mapped access to the map.
     */
    public int size()
    {
        return arrayValue.size();
    }

    /**
     * Provides mapped access to the map.
     */
    public void remove(int x)
    {
        arrayValue.remove(x);
    }
}
