package vermilion;

import java.util.ArrayList;

/**
 * Stores a pattern and the events that make it up. Unlike machine and wire nodes
 * this class is not just a representation but is also the actual data we work
 * from at runtime. The class extends UsefulFileObject so it can be written to
 * the composition.
 */
public class PatternNode extends UsefulFileObject
{
    /**
     * The name of the pattern, as shown on cues and in the pattern list.
     */
    public String patternID;

    /**
     * The length of this pattern in ticks.
     */
    public int patternLength;

    /**
     * The time signature of the pattern, in ticks per bar.
     */
    public int timeSig;

    /**
     * The names of any track groups that are part of this pattern. The list
     * stores only the names of the child nodes where the group tracks are
     * stored. Columns are manually found and created for the tracks in the
     * group.
     */
    public UsefulFileObjectList tracks;

    /**
     * Creates a new pattern, giving it a name and default length of 64.
     */
    public PatternNode(String name)
    {
        this(name, 64);
    }

    /**
     * Creates a new pattern of the given name and length, with default time
     * signature of 4.
     */
    PatternNode(String name, int length)
    {
        patternID = name;
        patternLength = length;
        timeSig = 4;
        tracks = new UsefulFileObjectList();
    }

    /**
     * Displays the pattern using its name, so it can be shown in lists etc.
     */
    @Override
    public String toString()
    {
        return patternID;
    }

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

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

    /**
     * Saves the pattern, it's parameters and trackgroups. Cues are stored
     * on PatternTrackNode objects as children to the pattern.
     */
    @Override
    public String saveImpl()
    {
        ArrayList<String> strs = new ArrayList<String>();

        strs.add(patternID);
        strs.add(String.valueOf(patternLength));
        strs.add(String.valueOf(timeSig));
        strs.add(tracks.save());

        return listToString(strs);
    }

    /**
     * Loads information for a pattern from the composition.
     */
    @Override
    public UsefulFileObject loadImpl(String str, int version)
    {
        PatternNode node = new PatternNode(null);

        ArrayList<String> data = stringToList(str);

        if (data.size() >= 3)
        {
            node.patternID = data.get(0);
            node.patternLength = Integer.parseInt(data.get(1));
            node.timeSig = Integer.parseInt(data.get(2));
            if (data.size() == 4) node.tracks = (UsefulFileObjectList) UsefulFileObjectList.load(data.get(3));
        }

        return node;
    }
}
