/*
 * Copyright (c) 2004-2017, by Alex Leigh.
 * All rights reserved.
 *
 * THIS IS UNPUBLISHED PROPRIETARY SOURCE CODE
 * The copyright notice above does not evidence any
 * actual or intended publication of such source code.
 */

package lc.mecha.util;

import lc.mecha.log.MechaLogger;
import lc.mecha.log.MechaLoggerFactory;

import java.io.*;

class StreamGobbler extends Thread {
    private static final MechaLogger logger = MechaLoggerFactory.getLogger(StreamGobbler.class);
    private final InputStream is;

    private final OutputStream os;

    private final String type;

    StreamGobbler(final InputStream is, final String type) {
        this(is, type, null);
    }

    private StreamGobbler(final InputStream is, final String type, final OutputStream redirect) {
        this.is = is;
        this.type = type;
        os = redirect;
    }

    @Override
    public void run() {
        try {
            PrintWriter pw = null;
            if (os != null) {
                pw = new PrintWriter(os);
            }

            final InputStreamReader isr = new InputStreamReader(is);
            final BufferedReader br = new BufferedReader(isr);
            String line;
            while ((line = br.readLine()) != null) {
                if (pw != null) {
                    pw.println(line);
                }
                logger.info(type + ">" + line);
            }
            if (pw != null) {
                pw.flush();
            }
        } catch (IOException ioe) {
            logger.warn("IO Exception", ioe);
        }
    }

    @Override
    public String toString() {
        return "StreamGobbler{" +
                "is=" + is +
                ", os=" + os +
                ", type='" + type + '\'' +
                "} " + super.toString();
    }
}
