// 
// Copyright (c) 2013-2016 Carsten Sonne Larsen <cs@innolan.dk>
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

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

namespace Ntp.Common.Log
{
    public abstract class TextLog : LogBase
    {
        protected TextLog(Severity treshold, string timeFormat)
            : base(treshold)
        {
            this.timeFormat = timeFormat;
            Initialized = false;
            suspended = false;
        }

        private readonly List<string> cache = new List<string>();

        protected readonly object Locker = new object();
        private readonly string timeFormat;
        protected bool Closed;
        protected bool Initialized;
        private bool suspended;
        private TextWriter writer;

        public bool ShowTimeStamp { get; set; }

        public bool ShowSeverity { get; set; }

        public override void Initialize()
        {
            lock (Locker)
            {
                if (!Initialized && !suspended && !Closed)
                {
                    writer = CreateWriter();
                    Initialized = true;
                }
            }
        }

        public override void Resume()
        {
            lock (Locker)
            {
                suspended = false;
            }
        }

        public override void Suspend()
        {
            lock (Locker)
            {
                if (writer != null)
                {
                    writer.Close();
                    writer.Dispose();
                    writer = null;
                }
                Initialized = false;
                suspended = true;
            }
        }

        public override void WriteLine(string text, Severity severity)
        {
            if (!Initialized)
                Initialize();

            if (!Initialized)
                return;

            lock (Locker)
            {
                if (Initialized && !suspended && cache.Count != 0)
                {
                    foreach (string line in cache)
                    {
                        writer.WriteLine(line);
                    }
                    writer.Flush();
                    cache.Clear();
                }
            }

            if (severity < Treshold)
                return;

            string severityText = string.Empty;

            if (ShowSeverity)
            {
                string pad = string.Empty;

                switch (severity)
                {
                    case Severity.Error:
                        severityText = "ERROR";
                        break;
                    case Severity.Warn:
                        severityText = "WARN";
                        pad = " ";
                        break;
                    case Severity.Notice:
                        severityText = "NOTICE";
                        break;
                    case Severity.Info:
                        severityText = "INFO";
                        pad = " ";
                        break;
                    case Severity.Debug:
                        severityText = "DEBUG";
                        break;
                    case Severity.Trace:
                        severityText = "TRACE";
                        break;
                    default:
                        throw new ApplicationException("Unknown severity level.");
                }

                severityText = string.Concat(" [", severityText, "] ", pad);
            }

            DateTime now = DateTime.Now;

            string stamp =
                ShowTimeStamp && timeFormat != null
                    ? now.ToString(timeFormat)
                    : string.Empty;

            string entry = string.Concat(stamp, severityText, text);

            lock (Locker)
            {
                if (Initialized)
                {
                    writer.WriteLine(entry);
                    writer.Flush();
                }
                else
                {
                    cache.Add(entry);
                }
            }
        }

        public override void WriteLine(Exception exception)
        {
            WriteLine(exception.Message, Severity.Error);
            WriteLine(exception.StackTrace, Severity.Debug);
        }

        public override void WriteLine(Exception exception, Severity severity)
        {
            if (severity < Treshold)
                return;

            WriteLine(exception.Message, severity);
            WriteLine(exception.StackTrace, severity);
        }

        protected abstract TextWriter CreateWriter();
    }
}