package com.jscape.inet.terminal.commands;

import com.jscape.inet.terminal.Terminal;

/**
 * DSR -- Device Status Report.
 */
public class DSRCommand
        implements ControlCommand {

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

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

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

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

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

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

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

    //----------------------------------------------------------------------------
    private void reportStatus(int code, Terminal terminal) {
        switch (code) {
            case 5:
                terminal.send("\033[0n");
                break;
            case 6:
                CPRCommand.getInstance().send(null, terminal);
                break;
            default:
                break;
        }
    }

}
