package com.jscape.inet.terminal.commands;

import com.jscape.inet.terminal.Terminal;

/**
 * CUU -- Cursor Up.
 * Moves the active position upward without altering the column position.
 * The number of lines moved is determined by the parameter.
 * A parameter value of zero or one moves the active position one line upward.
 * A parameter value of n moves the active position n lines upward.
 * If an attempt is made to move the cursor above the top margin,
 * the cursor stops at the top margin.
 */
public class CUUCommand
        implements ControlCommand {

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

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

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

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

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

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

    /**
     * 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 dst = (params != null && params.length > 0) ? params[0] : 1;
        dst = (dst == 0) ? 1 : dst;
        terminal.getScreen().getCursor().moveUp(dst);
    }

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

    /**
     * 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(CANONICAL_FORM).insert(2, params[0]);
            terminal.send(b.toString());
        }
    }

}
