using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Threading;
using C4IT.FASD.Base;
using static C4IT.Logging.cLogManager;

namespace FasdDesktopUi.Basics.UserControls
{
    public partial class TimerView : UserControl
    {
        #region Fields

        public event EventHandler<EventArgs> OnPauseStarted;

        private static List<DateTime> startTimes = new List<DateTime>();
        private static List<DateTime> endTimes = new List<DateTime>();
        private static List<DateTime> pausedTimesStart = new List<DateTime>();
        private static List<DateTime> pausedTimesEnd = new List<DateTime>();

        public static List<cF4SDCaseTime> caseTimes = new List<cF4SDCaseTime>();
        private static Dictionary<string, object> finalWorkingTimes = new Dictionary<string, object>();

        private static DispatcherTimer timer;
        private static TimeSpan elapsedTime;
        private static TimeSpan totalPausedTime = TimeSpan.Zero;
        private static TimeSpan pauseDuration;

        #endregion

        #region

        public TimerView()
        {
            InitializeComponent();
        }

        public static void ResetTimer()
        {
            startTimes.Clear();
            endTimes.Clear();
            pausedTimesEnd.Clear();
            pausedTimesStart.Clear();
            finalWorkingTimes.Clear();
            elapsedTime = TimeSpan.Zero;
            caseTimes.Clear();

            StartTimer();
        }

        public static void StartTimer()
        {
            try
            {
                startTimes?.Add(DateTime.UtcNow);
                timer?.Start();
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        public void StopTimer()
        {
            try
            {
                endTimes?.Add(DateTime.UtcNow);
                timer?.Stop();
                UpdateTimerControl();
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        private void UserControl_Initialized(object sender, EventArgs e)
        {
            try
            {
                ResetTimer();

                timer = new DispatcherTimer(TimeSpan.FromSeconds(1.0), DispatcherPriority.Loaded, new EventHandler((s, args) =>
                {
                    try { UpdateTimerControl(); }
                    catch { }
                }),
                Dispatcher.CurrentDispatcher);
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        private void UpdateTimerControl()
        {
            try
            {
                TimerControl.Text = elapsedTime.ToString(@"hh\:mm\:ss");
                elapsedTime = elapsedTime.Add(TimeSpan.FromSeconds(1.0));
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        public static Dictionary<string, object> GetWorkTimes()
        {
            try
            {
                var currentDate = DateTime.Now.Date.ToString("d");
                var startDateTime = startTimes.First();
                var endDateTime = DateTime.UtcNow;
                var bruttoWorkingTime = TimeSpan.Zero;
                var nettoWorkingTime = TimeSpan.Zero;

                if (pausedTimesStart.Count == 0)
                {
                    totalPausedTime = TimeSpan.Zero;
                }

                if (pausedTimesEnd.Count > 0)
                {
                    totalPausedTime = TimeSpan.Zero;

                    for (int i = 0; i < pausedTimesStart.Count; i++)
                    {
                        var start = pausedTimesStart[i];
                        var end = pausedTimesEnd[i];

                        pauseDuration = end - start;

                        totalPausedTime += pauseDuration;
                    }
                }

                bruttoWorkingTime = endDateTime - startDateTime;

                nettoWorkingTime = bruttoWorkingTime - totalPausedTime;

                finalWorkingTimes = new Dictionary<string, object>()
                {
                    {"CurrentDate", currentDate},
                    {"StartTime", startTimes.First()},
                    {"EndTime", endDateTime },
                    {"BruttoWorkingTime", bruttoWorkingTime },
                    {"NettoWorkingTime", nettoWorkingTime.TotalSeconds },
                    {"TotalPausedTime", totalPausedTime }
                };
            }
            catch (Exception E)
            {
                LogException(E);
            }

            return finalWorkingTimes;
        }

        #endregion

        #region Click-Events

        public void EndPause()
        {
            try
            {
                if (timer?.IsEnabled == true)
                    return;

                timer?.Start();
                pausedTimesEnd?.Add(DateTime.UtcNow);

                caseTimes.Add(new cF4SDCaseTime()
                {
                    StatusId = CaseStatus.InProgress,
                    CaseTime = DateTime.UtcNow
                });
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }

        private void PauseButton_Click()
        {
            try
            {
                timer?.Stop();
                pausedTimesStart?.Add(DateTime.UtcNow);

                caseTimes.Add(new cF4SDCaseTime()
                {
                    StatusId = CaseStatus.OnHold,
                    CaseTime = DateTime.UtcNow
                });

                if (OnPauseStarted != null)
                    OnPauseStarted?.Invoke(this, new EventArgs());
            }
            catch (Exception E)
            {
                LogException(E);
            }
        }


        private void Border_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            PauseButton_Click();
        }

        #endregion

        private void Border_TouchDown(object sender, TouchEventArgs e)
        {
            PauseButton_Click();
        }
    }
}
