﻿using System.Linq;
using Autofac.Features.Indexed;
using NLog;
using Pal.Core;
using Pal.Core.Interface.Wrappers;
using Pal.DomainServices.Interfaces;
using Pal.Services.Interfaces.LogFiles;

namespace Pal.DomainServices
{
    public class LogReaderEngine : ILogReaderEngine
    {
        private readonly IIndex<SourceFileEnum, ILogFileManager> _eventManagers;
        private readonly ILogger _logger;
        private readonly IEnumWrapper _enumWrapper;

        public LogReaderEngine(ILogger logger, IIndex<SourceFileEnum, ILogFileManager> eventManagers, IEnumWrapper enumWrapper)
        {
            _logger = logger;
            _eventManagers = eventManagers;
            _enumWrapper = enumWrapper;
        }

        public bool Start(SourceFileEnum sourceFile)
        {
            var result = _eventManagers[sourceFile].Start();
            if (result)
            {
                _logger.Debug("Start " + sourceFile + " log watching");
            }
            else
            {
                _logger.Debug("Could not start " + sourceFile + " log watching");
            }
            return result;
        }

        public bool End(SourceFileEnum sourceFile)
        {
            var result = _eventManagers[sourceFile].Stop();
            if (result)
            {
                _logger.Debug("Stop " + sourceFile + " log watching");
            }
            else
            {
                _logger.Debug("Could not stop " + sourceFile + " log watching");
            }
            return result;
        }

        public bool StartAll()
        {
            var sourceFiles = _enumWrapper.GetValues<SourceFileEnum>().ToList();
            if (!sourceFiles.Any())
            {
                _logger.Debug("Source file list to start is empty");
                return false;
            }

            var allStart = sourceFiles.Select(x => _eventManagers[x].Start())
                                      .All(startResult => startResult);

            if (!allStart)
            {
                _logger.Debug("Could not start all log watching");
                return false;
            }

            _logger.Debug("Start all log watching");
            return true;
        }

        public bool EndAll()
        {
            var sourceFiles = _enumWrapper.GetValues<SourceFileEnum>().ToList();
            if (!sourceFiles.Any())
            {
                _logger.Debug("Source file list to stop is empty");
                return false;
            }

            var allStart = sourceFiles.Select(x => _eventManagers[x].Stop())
                                      .All(startResult => startResult);

            if (!allStart)
            {
                _logger.Debug("Could not stop all log watching");
                return false;
            }

            _logger.Debug("Stop all log watching");
            return true;
        }
    }
}