package com.jscape.inet.terminal.commands;

import com.jscape.inet.terminal.Terminal;

/**
 * CUP -- Cursor Position.
 * The CUP sequence moves the active position to the position specified
 * by the parameters. This sequence has two parameter values, the first
 * specifying the line position and the second specifying the column position.
 * A parameter value of zero or one for the first or second parameter moves
 * the active position to the first line or column in the display, respectively.
 * The default condition with no parameters present is equivalent to a cursor
 * to home action. In the VT100, this control behaves identically with its
 * format effector counterpart, HVP.
 */
public class CUPCommand
        implements ControlCommand {

    public static final String CANONICAL_FORM = "\033[H";
    private static final CUPCommand INSTANCE = new CUPCommand();

    //----------------------------------------------------------------------------

    /**
     * Returns one and only one instance of this type.
     *
     * @return one and only one instance of this type.
     */
    public static final CUPCommand getInstance() {
        return INSTANCE;
    }

    //----------------------------------------------------------------------------

    /**
     * Private constructor to prevent uncontrolled creation.
     */
    private CUPCommand() {
    }

    //----------------------------------------------------------------------------

    /**
     * Executes command giving parameters and <code>Terminal</code> object.
     *
     * @param params   array of <code>int</code> command parametrs.
     * @param terminal target <code>Terminal</code> object.
     */
    public void execute(int[] params, Terminal terminal) {
        int row = 1;
        int col = 1;

        if (params != null) {
            if (params.length > 0) {
                row = params[0];
            }
            if (params.length > 1) {
                col = params[1];
            }
        }

        terminal.getScreen().getCursor().moveTo(row, col);
    }

    //----------------------------------------------------------------------------

    /**
     * Sends command to remote host.
     *
     * @param params   command parameters.
     * @param terminal target <code>Terminal</code> object to send command.
     */
    public void send(int[] params, Terminal terminal) {
        if (params == null || params.length == 0) {
            terminal.send(CANONICAL_FORM);
        } else {
            StringBuffer b = new StringBuffer("\033[");

            if (params.length > 0) {
                b.append(params[0]);
            }
            if (params.length > 1) {
                b.append(';').append(params[1]);
            }

            b.append('H');
            terminal.send(b.toString());
        }
    }
}
