package vermilion;

import java.util.ArrayList;
import java.util.TreeMap;

/**
 * Represents a pattern cue currently being played on a master track. Stores
 * the machine ID the pattern cues are to be sent to and the pattern node that
 * was cued.
 * This is created when a pattern cue is played and is kept in a list by the
 * SystemComposer where it is used to generate the cues that occur in the
 * pattern. When the pattern is finished it will be removed from the list by the
 * composer.
 */
class PlayingPattern
{
    public int nextPatternTick;
    public PatternNode pattern;
    //public String machineName;

    public long nextTickTime = 0;

    private int patternTimeSig = 4;
    private TreeMap<Integer, ArrayList<PlaybackEvent>> events;

    public PlayingPattern(PatternNode node, String machName, String machID, long startTime)
    {
        pattern = node;
        //machineName = machName;
        nextTickTime = startTime;

        events = new TreeMap<Integer, ArrayList<PlaybackEvent>>();

        // TODO: Implement/read pattern time signature.
        patternTimeSig = 4;

        String locn = "Patterns/" + machName + "/" + node.patternID;
        ArrayList<UsefulFileObject> columns = Main.document.getChildren(locn);

        if (columns == null) return;

        for (int x = 0; x < node.patternLength; x++)
        {
            ArrayList<PlaybackEvent> tickList = new ArrayList<PlaybackEvent>();

            for (int y = 0; y < columns.size(); y++)
            {
                PatternTrackNode column = (PatternTrackNode) columns.get(y);
                ParameterBase param = (ParameterBase) column.commands.get(x);
                if (param != null) tickList.add(new PlaybackEvent(machID, column.paramName, param));
            }

            events.put(x, tickList);
        }
    }

    void getEvents(ArrayList<Object> buffer, int barsPerTenMinutes)
    {
        System.out.println(pattern.patternID + " tick " + nextPatternTick);

        ArrayList<PlaybackEvent> tickEvts = (ArrayList<PlaybackEvent>) events.get(nextPatternTick);
        buffer.addAll(tickEvts);

        nextTickTime += 600 * SystemComposer.TIME_RES / barsPerTenMinutes / patternTimeSig;
        nextPatternTick++;
    }
}
