/*
 * @author Ranides Atterwim <ranides@gmail.com>
 * @copyright Ranides Atterwim
 * @license WTFPL
 * @url http://ranides.net/projects/assira.junit
 */
package net.ranides.assira.junit;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.IllegalCharsetNameException;

/**
 *
 * @author Ranides Atterwim <ranides@gmail.com>
 */
public final class BenchmarkRunner {
    
    private BenchmarkRunner() {
        // utility class
    }
    
    public static void run(Class<?> clazz) {
        OutputStream collector = ConsoleObserver.get();
        new com.google.caliper.Runner().run(
            "--trials", "3",
//            "--warmupMillis", "100",
//            "--runMillis", "100",
//            "-Dparam=0",
            clazz.getName()
        );
        BenchmarkReport.print(System.out, collector.toString());
    }
    
    
    static final class ConsoleObserver extends OutputStream {

        private final PrintStream stdout;
        private final ByteArrayOutputStream stream;

        private ConsoleObserver(PrintStream stdout) {
            this.stdout = stdout;
            this.stream = new ByteArrayOutputStream();
        }

        public static ConsoleObserver get() {
            ConsoleObserver observer = new ConsoleObserver(System.out);
            System.setOut(new PrintStream(observer));
            return observer;
        }

        @Override
        public void write(int data) throws IOException {
            stdout.write(data);
            stream.write(data);
        }

        @Override
        public void write(byte[] data) throws IOException {
            stdout.write(data);
            stream.write(data);
        }

        @Override
        public void write(byte[] data, int offset, int length) throws IOException {
            stdout.write(data, offset, length);
            stream.write(data, offset, length);
        }

        @Override
        public void close() throws IOException {
            stream.close();
            System.setOut(stdout);
        }

        @Override
        public void flush() throws IOException {
            stdout.flush();
            stream.flush();
        }

        @Override
        public String toString() {
            return toString("UTF-8");
        }

        public String toString(String charset) throws IllegalCharsetNameException {
            try {
                return stream.toString(charset);
            } catch (UnsupportedEncodingException cause) {
                throw (IllegalCharsetNameException)new IllegalCharsetNameException(charset).initCause(cause);
            }
        }

    }


}

