package com.mockobjects.io;

import com.mockobjects.ExpectationCounter;
import com.mockobjects.ExpectationSegment;
import com.mockobjects.util.Verifier;

import java.io.OutputStream;
import java.io.PrintStream;

public class MockPrintStream extends PrintStream {
    private ExpectationCounter myPrintlnCalls = new ExpectationCounter("MockPrintStream.println calls");
    private ExpectationSegment mySegment = new ExpectationSegment("String segment");
    private PrintStream myOldErrorStream;

    public MockPrintStream() {
        this(null);
    }

    public MockPrintStream(OutputStream out) {
        super(out);
    }

    public MockPrintStream(OutputStream out, boolean autoFlush) {
        super(out, autoFlush);
    }

    public void becomeErrorStream() {
        myOldErrorStream = System.err;
        System.setErr(this);
    }

    public void println(Object anObject) {
        myPrintlnCalls.inc();
    }

    public void println(String aString) {
        println((Object) aString);
        mySegment.setActual(aString);
    }

    public void restoreErrorStream() {
        System.setErr(myOldErrorStream);
    }

    public void setExpectedPrintlnCalls(int calls) {
        myPrintlnCalls.setExpected(calls);
    }

    public void setExpectedStringSegment(String aString) {
        mySegment.setExpected(aString);
    }

    public void verify() {
        Verifier.verifyObject(this);
    }
}
