package com.jscape.inet.terminal.commands;

import com.jscape.inet.terminal.Screen;
import com.jscape.inet.terminal.Terminal;

/**
 * DECSTBM -- Set Top and Bottom Margins.
 * This sequence sets the top and bottom margins to define the scrolling region.
 * The first parameter is the line number of the first line in the scrolling
 * region; the second parameter is the line number of the bottom line in the
 * scrolling region. Default is the entire screen (no margins).
 * The minimum size of the scrolling region allowed is two lines, i.e.,
 * the top margin must be less than the bottom margin.
 * The cursor is placed in the home position (see Origin Mode DECOM).
 */
public class DECSTBMCommand
        implements ControlCommand {

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

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

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

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

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

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

    /**
     * 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) {
        Screen s = terminal.getScreen();

        if (params == null || params.length == 0) {
            s.setMargins(1, s.getMaxRow());
        } else {
            int upper = (params[0] == 0) ? 1 : params[0];
            int bottom = s.getMaxRow();

            if (params.length > 1) {
                bottom = (params[1] == 0) ? s.getMaxRow() : params[1];
            }

            s.setMargins(upper, bottom);
        }
    }

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

    /**
     * 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[");

            for (int i = 0; i < params.length; ++i) {
                b.append(params[i]);
                if (i < (params.length - 1)) {
                    b.append(';');
                }
            }

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

}
