using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Collections.Specialized;
using System.Configuration.Provider;

namespace Winson.Framework.LogProviders
{
    /// <summary>
    /// 将日志写入Windows事务管理器
    /// </summary>
    partial class Log2WinProvider : LogProviderBase
    {
        #region 属性
        private string _eventSource;
        #endregion

        public override void Initialize(string name, NameValueCollection config)
        {
            if (config == null)
            {
                throw new ArgumentNullException("没有相关配置!");
            }

            if (String.IsNullOrEmpty(name))
            {
                name = "Log2WinProvider";
            }

            if (String.IsNullOrEmpty(config["description"]))
            {
                config.Remove("description");
                config.Add("description", "创建Windows日志提供者");
            }

            base.Initialize(name, config);

            if (config["eventSource"] == null)
            {
                // 默认日志文件路径
                config["eventSource"] = "Winson.Framework";
            }
            _eventSource = config["eventSource"];
            config.Remove("eventSource");


            //如果有多余的属于，则抛出异常
            if (config.Count > 0)
            {
                string attr = config.GetKey(0);
                if (!String.IsNullOrEmpty(attr))
                    throw new ProviderException("未指定的属性: " + attr);
            }
        }

        public override bool OutputErrLog(string methodName, string parametersList, Exception exception)
        {
            string __log = "";
            string __event = "";

            __log = "Application";
            __event = "==========begin==========\n";
            __event += DateTime.Now.ToString("f", DateTimeFormatInfo.InvariantInfo) + "\n";
            __event += "Method:" + methodName + "\n";
            __event += "Parameters:" + parametersList + "\n";
            __event += "Message:" + exception.Message + "\n";
            __event += "Trace:" + exception.StackTrace + "\n";
            __event += "==========end==========\n";

            try
            {
                if (!EventLog.SourceExists(_eventSource))
                    EventLog.CreateEventSource(_eventSource, __log);

                EventLog.WriteEntry(_eventSource, __event,
                    EventLogEntryType.Error);
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

            return false;
        }

    }
}
