package com.jscape.inet.terminal.commands;

import com.jscape.inet.terminal.Terminal;

/**
 * SM -- Set Mode.
 * Causes one or more modes to be set within the VT100 as specified by
 * each selective parameter in the parameter string.
 * Each mode to be set is specified by a separate parameter.
 * A mode is considered set until it is reset by a reset mode (RM)
 * control sequence.
 */
public class SMCommand
        implements ControlCommand {

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

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

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

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

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

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

    /**
     * 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) {
        if (params != null && params.length > 0) {
            for (int i = 0; i < params.length; ++i) {
                setMode(params[i], terminal);
            }
        }
    }

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

    /**
     * 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('h');
            terminal.send(b.toString());
        }
    }

    //----------------------------------------------------------------------------
    private void setMode(int code, Terminal terminal) {
        switch (code) {
            case 6:
                terminal.getScreen().setOriginMode(true);
                break;
            case 7:
                terminal.setAutoWrapMode(true);
                break;
            case 20:
                terminal.setLNMMode(true);
                break;
            default:
                break;
        }
    }

}
