using System;
using System.Diagnostics.Tracing;
using System.IO;
using Microsoft.Practices.EnterpriseLibrary.SemanticLogging;
using Microsoft.Practices.EnterpriseLibrary.SemanticLogging.Sinks;
using Valg.EVA.Skanning.Contracts;

namespace Valg.EVA.Skanning.Diagnostics
{
    
    
    
    
    
    public class InProcessLoggingSinkConfigurator
    {
        private readonly IDiagnosticsConfiguration diagnosticsConfiguration;
        public InProcessLoggingSinkConfigurator(IDiagnosticsConfiguration diagnosticsConfiguration)
        {
            this.diagnosticsConfiguration = diagnosticsConfiguration;
        }

        public void ConfigureLoggingSinks(string processName)
        {
            var sinkType = "rollingFlatFile";
            if (diagnosticsConfiguration.IsInProcessFileLoggingSinkEnabled)
            {
                string filename = null;
                try
                {
                    var listener1 = new ObservableEventListener();
                    listener1.EnableEvents(EvaSkanningEventSource.Log, EventLevel.LogAlways);

                    filename = Path.Combine(diagnosticsConfiguration.LogDirectory, "logfile.log");
                    listener1.LogToRollingFlatFile(filename, 4096, "yyyyMMdd", RollFileExistsBehavior.Increment, RollInterval.Day, new FlatFileEventTextFormatter(), isAsync: true);
                    EvaSkanningEventSource.Log.InProcessLoggingSinkConfigurationSuccess(processName, filename, sinkType);
                }
                catch (Exception e)
                {
                    EvaSkanningEventSource.Log.InProcessLoggingSinkConfigurationFailed(processName, e.ToString(), filename, sinkType);
                }
            }
            else
            {
                EvaSkanningEventSource.Log.InProcessLoggingSinkConfigurationNotEnabled(processName, sinkType);
            }
        }
    }
}
