using System;
using System.Collections;
using System.Threading;
using System.IO;
using Microsoft.SPOT;

namespace Logger
{
    // Simple To File Logger.  All messages a written out to a flat text file.
    public class FileLogger : LoggerEventHandler
    {
        StreamWriter stream = null;
        bool append = true;

        public FileLogger(String filename)
        {
            if (filename != null)
            {
                FileMode fm;

                if (append) 
                    fm = FileMode.Append;
                else 
                    fm = FileMode.Create;
                FileStream fs = new FileStream(filename, fm, FileAccess.Write, FileShare.Read);
                stream = new StreamWriter(fs);
            }
        }

        override protected void log(LoggerMessage message)
        {
            if (stream == null) return;
            // string time = System.DateTime.FromFileTime(message.time).ToString();
            string test = "[" + time + " [" + message.level + ":" + message.level_desc + " (" + message.tag + ")] " + message.message + " ]\r\n";
            stream.Write("[" + time + " [" + message.level + ":" + message.level_desc + " (" + message.tag + ")] " + message.message + " ]\r\n");
        }

        protected override void onShutdown()
        {
            if (stream != null)
            {
                stream.Flush();
                stream.Close();
            }
        }

        // Flag to append the text file.  If this flag is not set it will overwrite.
        public void setAppend(bool flag)
        {
            this.append = flag;
        }

        // Get's append flag
        public bool getAppend()
        {
            return append;
        }
    }
}
