package com.jscape.inet.terminal.commands;

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

/**
 * EL -- Erase In Line.
 * Erases some or all characters in the active line according to the parameter.
 */
public class ELCommand
        implements ControlCommand {

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

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

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

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

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

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

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

    //----------------------------------------------------------------------------
    private void eraseLine(int code, Terminal terminal) {
        Screen s = terminal.getScreen();
        int col = s.getCursor().column();
        int maxCol = s.getMaxCol();

        switch (code) {
            case 0:
                s.eraseLine(col, maxCol);
                break;
            case 1:
                s.eraseLine(1, col);
                break;
            case 2:
                s.eraseLine(1, maxCol);
                break;
            default:
                break;
        }
    }
}
