package vermilion;

import java.awt.event.KeyEvent;

/**
 * A tracker column that represents a continuous slider control as a four
 * digit number.
 */
public class JTrackerColumnNote extends JTrackerColumn
{
    public final String[] noteNames = new String[]
        { "A-", "A#", "B-", "C-", "C#", "D-", "D#", "E-", "F-", "F#", "G-", "G#"  };

    public final char[] noteKeys = new char[]
        { 'z', 's', 'x', 'd', 'c', 'v', 'g', 'b', 'h', 'n', 'j', 'm',
          'q', '2', 'w', '3', 'e', 'r', '5', 't', '6', 'y', '7', 'u', 'i' };

    /**
     * Constructs a new column for representing a slider parameter.
     */
    public JTrackerColumnNote(String colName, String paramName, PatternNode pattern, int offset, PatternTrackNode commands)
    {
        super(colName, paramName, pattern, offset, 6, commands);
    }

    /**
     * Gets note value entries from the pattern for display.
     */
    @Override
    public String getEntry(int rowNum)
    {
        ParameterNote command = (ParameterNote) commandList.commands.get(rowNum);

        if (command != null)
        {
            int noteValue = command.value;
            int fineTune = noteValue % 100;
            int noteNum = noteValue / 100;

            int noteNote = noteNum % 12;
            int noteOct = noteNum / 12;

            String noteVal = noteNames[noteNote];
            String octVal = String.valueOf(noteOct);
            if (octVal.length() < 2) octVal = "0" + octVal;
            noteVal += octVal;

            octVal = String.valueOf(fineTune);
            if (octVal.length() < 2) octVal = "0" + octVal;
            noteVal += octVal;

            return noteVal;
        }
        else return "------";
    }

    /**
     * Interprets keypresses and creates or modifies slider cues.
     */
    @Override
    public boolean setEntry(int rowNum, int cursorPos, KeyEvent key)
    {
        if (key.getKeyCode() == KeyEvent.VK_BACK_SPACE ||
            key.getKeyCode() == KeyEvent.VK_DELETE)
        {
            commandList.commands.remove(rowNum);
            return true;
        }

        int noteVal = -1;
        for (int x = 0; x < noteKeys.length; x++)
        {
            if (key.getKeyChar() == noteKeys[x]) noteVal = x;
        }
        if (noteVal < 0) return false;

        ParameterNote newNode = new ParameterNote(columnName, true);
        newNode.value = (noteVal+3+36)*100;
        commandList.commands.put(rowNum, newNode);

        return true;
    }
}

// TODO: Patterns not saved before playback... Maybe autosave every 10 sec
// and just b4 playback. ...locking rhubarb rhubarb rhubarb...