package com.jscape.inet.terminal.commands;

import com.jscape.inet.terminal.Terminal;

/**
 * CUB -- Cursor Backward.
 * The CUB sequence moves the active position to the left.
 * The distance moved is determined by the parameter.
 * If the parameter value is zero or one, the active position is moved
 * one position to the left. If the parameter value is n,
 * the active position is moved n positions to the left.
 * If an attempt is made to move the cursor to the left of the left margin,
 * the cursor stops at the left margin.
 */
public class CUBCommand
        implements ControlCommand {

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

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

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

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

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

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

    /**
     * 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().moveLeft(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());
        }
    }
}
