package org.ow2.jonas.cluster.daemon;

import org.objectweb.util.monolog.api.BasicLevel;
import org.objectweb.util.monolog.api.Logger;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * Allow to trace errors/output of a process.
 */
public class CmdReaderThread implements Runnable {

    /**
     * Input stream containing information.
     */
    private InputStream is;

    /**
     * Should send as error or debug message.
     */
    private boolean isErrorMessage = false;

    /**
     * Logger to use.
     */
    private Logger logger = null;

    /**
     * Cmd associated with the reader.
     */
    private String cmd = null;

    /**
     * Constructor.
     *
     * @param logger         logger
     * @param cmd            command
     * @param is             given input stream
     * @param isErrorMessage Should send as error or debug message
     */
    public CmdReaderThread(final Logger logger, final String cmd, final InputStream is, final boolean isErrorMessage) {
        this.is = is;
        this.isErrorMessage = isErrorMessage;
        this.logger = logger;
        this.cmd = cmd;
    }

    /**
     * Thread execution printing information received.
     */
    public void run() {
        try {
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String str = null;
            while ((str = br.readLine()) != null) {
                if (isErrorMessage) {
                    this.logger.log(BasicLevel.ERROR, "<" + cmd + "> " + str);
                } else {
                    this.logger.log(BasicLevel.DEBUG, "<" + cmd + "> " + str);
                }
            }
            // close input stream
            is.close();
        } catch (Exception e) {
            this.logger.log(BasicLevel.ERROR, e.getMessage());
            e.printStackTrace();
        }
    }

}