package com.jscape.inet.terminal.commands;

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

/**
 * ED -- Erase In Display.
 * This sequence erases some or all of the characters in the display according
 * to the parameter.
 */
public class EDCommand
        implements ControlCommand {

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

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

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

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

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

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

    /**
     * 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) {
            erase(0, terminal);
        } else {
            for (int i = 0; i < params.length; ++i) {
                erase(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('J');
            terminal.send(b.toString());
        }
    }

    //----------------------------------------------------------------------------
    private void erase(int code, Terminal terminal) {
        Screen s = terminal.getScreen();

        switch (code) {
            case 0:
                s.erase(s.getMaxRow(), s.getMaxCol());
                break;
            case 1:
                s.erase(1, 1);
                break;
            case 2:
                s.erase();
                break;
            default:
                break;
        }
    }

}
