//StealthNet
//Copyright (C) 2010 T.Norad

//This program is free software; you can redistribute it and/or
//modify it under the terms of the GNU General Public License
//as published by the Free Software Foundation; either version 2
//of the License, or (at your option) any later version.

//This program is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//GNU General Public License for more details.

//You should have received a copy of the GNU General Public License
//along with this program; if not, write to the Free Software
//Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace Regensburger.RShare
{
    public sealed class FileLogger : ILogObserver
    {
        // contains the logfile directory.
        private String m_LogFileDir = null;

        /// <summary>
        /// Constructor.
        /// Initialize this logger with the directory for the logfiles. 
        /// </summary>
        /// <param name="logDirectory">path of the directory to store the logfiles</param>
        public FileLogger(String logDirectory)
        {
            if (logDirectory == null)
                throw new ArgumentNullException("logDirectory");
            m_LogFileDir = logDirectory;

            Logger.Instance.Attach(this);
        }

        /// <summary>
        /// Method implementation from ILogObserver
        /// </summary>
        public void NewLogEntry(LogEntry logEntry)
        {
            // create logfile name
            String filename = string.Format("{0:yyyy}-{0:MM}-{0:dd}.log", DateTime.Now);
            // compine path and name and set it as member value
            String logPath = Path.Combine(this.m_LogFileDir, filename);

            try
            {
                StreamWriter logFileStreamWriter = new StreamWriter(new FileStream(logPath, FileMode.Append, FileAccess.Write, FileShare.Read), Encoding.UTF8);
                logFileStreamWriter.WriteLine("{0:T}: {1}", logEntry.TimeStamp, logEntry.Text);
                if (logEntry.ThrownException != null)
                    logFileStreamWriter.WriteLine(logEntry.ThrownException.ToString());
                logFileStreamWriter.Flush();
                logFileStreamWriter.Close();
            }
            catch
            {
            }
        }
    }
}
