//------------------------------------------------------------------------------
// <copyright file="TestLog.java" company="Microsoft">
//      Copyright (c) Microsoft Corporation.  All rights reserved.
// </copyright>
// <summary>
//      Implement output logging
// </summary>
//------------------------------------------------------------------------------

import java.io.*;
import java.nio.*;
import java.nio.channels.*;

public class TestLog {
    private FileOutputStream fs;
    private FileChannel writer;
    private PrintWriter pw;
    String logfile;
    
    TestLog(String filename)
    {
        try{
            this.logfile = filename;
            fs = new FileOutputStream(new File(filename), true);
            writer = fs.getChannel();
            pw = new PrintWriter(fs);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    void WriteConsole(String format, Object... args)
    {
        try{
            writer.write(createBuffer(format + "%n", args));
        } catch(Exception e) {
            e.printStackTrace();
        }
        System.out.printf(format + "%n", args);
    }
    
    
    void WriteFails(String format, Object... args)
    {
        try {
            writer.write(createBuffer(format + "%n", args));
        } catch(Exception e) {
            e.printStackTrace();
        }
        System.out.printf(format + "%n", args);
    }
    
    void WriteLine(String format, Object... args)
    {
        try{
            writer.write(createBuffer(format, args));
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    void WriteException(Throwable e)
    {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        WriteLine(sw.toString());
    }
    
    void Flush()
    {
        try{
            fs.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    void Close()
    {
        try{
            fs.close();
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
    
    private ByteBuffer createBuffer(String format, Object... args) //does not exist in C# implementation
    {
        String text = String.format(format + "%n", args);
        ByteBuffer buf = ByteBuffer.allocate(text.length()+2);
        buf.put(text.getBytes());
        buf.flip();
        return buf;
    }
    
}
