package vermilion;

import java.awt.event.KeyEvent;

/**
 * A tracker column that represents a sample bank index as a 3 digit number.
 */
public class JTrackerColumnSample extends JTrackerColumn
{
    /**
     * Constructs a new column for representing a sample parameter.
     */
    public JTrackerColumnSample(String colName, String paramName, PatternNode pattern, PatternTrackNode commands, int trackNumber)
    {
        super(colName, paramName, pattern, 3, commands, trackNumber);
    }

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

        if (command != null)
        {
            return valueToStr(command);
        }
        else return "---";
    }

    private String valueToStr(ParameterSample command)
    {
        String str = String.valueOf(command.value);
        if (str.length() == 1) {
            str = "00" + str;
        } else if (str.length() == 2) {
            str = "0" + str;
        }
        return str;
    }

    /**
     * Interprets keypresses and creates or modifies sample index 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;
        }

        char keyChar = key.getKeyChar();
        if (keyChar < '0' || keyChar > '9') return false;

        ParameterSample newNode = new ParameterSample(0);
        ParameterSample oldNode = (ParameterSample) commandList.commands.get(rowNum);

        char[] commandChars = valueToStr(newNode).toCharArray();
        if (oldNode != null) commandChars = valueToStr(oldNode).toCharArray();

        commandChars[cursorPos] = keyChar;
        String newVal = new String(commandChars);
        newNode.value = Integer.parseInt(newVal);

        commandList.commands.put(rowNum, newNode);

        return true;
    }

    /**
     * Returns a helper/info display message for the current column, cursor
     * position and cue if one exists.
     */
    @Override
    public String getCursorDescription(int rowNum, int cursorPos)
    {
        // TODO: Description of entry if any, cursor pos.
        return "Sample value for " + parameterName + " - Keys 1, 2, 3, 4...";
    }
}