using System;
using System.Windows.Threading;
using Valg.EVA.Skanning.Services.SystemSettings;
using Prism.Events;

namespace Valg.EVA.Skanning.JobManagement.Startup.DataRefresh
{
    public class DataRefresher : IDataRefresher
    {
        private readonly ISystemSettingsService systemSettings;
        private readonly IEventAggregator eventAggregator;
        private static DispatcherTimer timerForRefreshingAllData;
        private bool refreshingAllDataIsrunning;
        private static DispatcherTimer timerForRefreshingTransferData;

        public DataRefresher(ISystemSettingsService systemSettings, IEventAggregator eventAggregator)
        {
            this.systemSettings = systemSettings;
            this.eventAggregator = eventAggregator;
            this.eventAggregator.GetEvent<EnableDataRefreshEvent>().Subscribe(EnableDataRefreshEventHandler);

            InitTimer();
            InitTransferDataUpdateTimer();
        }

        private void EnableDataRefreshEventHandler(EnableDataRefreshEventArgs enableRefreshEventArgs)
        {
            if (enableRefreshEventArgs.Enable && !timerForRefreshingAllData.IsEnabled)
            {
                Start();
            }
            else if (!enableRefreshEventArgs.Enable && timerForRefreshingAllData.IsEnabled)
            {
                Stop();
            }
        }

        public void Start()
        {
            refreshingAllDataIsrunning = true;
            timerForRefreshingAllData.Start();
            timerForRefreshingTransferData.Start();
        }

        public void Stop()
        {
            timerForRefreshingAllData.Stop();
            timerForRefreshingTransferData.Stop();
            refreshingAllDataIsrunning = false;
        }

        private void InitTimer()
        {
            var interval = systemSettings.GetDataRefreshInterval();
            timerForRefreshingAllData = new DispatcherTimer();
            timerForRefreshingAllData.Tick += (o, args) => RefreshAllData();
            timerForRefreshingAllData.Interval = TimeSpan.FromSeconds(interval);
        }

        private void InitTransferDataUpdateTimer()
        {
            var interval = systemSettings.GetTransferStatusCheckTimeoutInterval();
            timerForRefreshingTransferData = new DispatcherTimer();
            timerForRefreshingTransferData.Tick += (o, args) => RefreshTransferData();
            timerForRefreshingTransferData.Interval = TimeSpan.FromSeconds(interval);
        }

        private void RefreshTransferData()
        {
            eventAggregator.GetEvent<DataRefreshRequestedEvent>().Publish(new DataRefreshRequestedEventArgs(DataRefreshType.TransferDataOnly));
        }

        public void RefreshAllData()
        {
            eventAggregator.GetEvent<DataRefreshRequestedEvent>().Publish(new DataRefreshRequestedEventArgs());
        }

        public bool RefreshingAllDataIsrunning { get { return refreshingAllDataIsrunning; } }
    }
}
