using Microsoft.WindowsAPICodePack.Taskbar;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows.Media;
using System.Windows.Threading;

namespace Nappat.Testing.WPF
{
    public class TestProgressBar
    {
        private MainWindow mainWindow;
        private TaskbarManager taskbar = TaskbarManager.Instance;
        private int maximum = 0;
        private DateTime startTime;

        public bool CanProgress = false;

        public TestProgressBar(MainWindow mainWindow)
        {
            this.mainWindow = mainWindow;
        }

        public void Progress(DataSender dataSender)
        {
            TimeSpan timeDiference = (dataSender.LogMessages.Time - startTime);
            double progress = timeDiference.TotalSeconds;
            if (progress < 0)
                progress = 0;
            mainWindow.progressBar.Value = progress;
            mainWindow.startTimeLabel.Content = (progress / maximum).ToString("P0", CultureInfo.InvariantCulture);
            var temp = (progress / maximum);
            if (temp < 0)
                temp = temp * -1;
            string progressString = (temp * 100).ToString("F0", CultureInfo.CreateSpecificCulture("en-US"));
            int progressNumber;
            bool result1 = Int32.TryParse(progressString, out progressNumber);
            if (result1)
                taskbar.SetProgressValue(progressNumber, 100);

        }

        public void Start(DataSender dataSender)
        {
            mainWindow.progressBar.Foreground = Brushes.Green;
            taskbar.SetProgressState(TaskbarProgressBarState.Normal);
            startTime = DateTime.Now;
            maximum = (int)(dataSender.TestTime / 100);
            mainWindow.progressBar.Maximum = maximum;
            mainWindow.finishTimeLabel.Content = new TimeSpan((dataSender.TestTime * 100000));
            CanProgress = true;
        }

        public void Stop(DataSender dataSender)
        {
            CanProgress = false;
            if (dataSender.LogMessages.Severity == "Info")
            {
                mainWindow.progressBar.Value = maximum;
                taskbar.SetProgressValue(maximum, maximum);
                mainWindow.startTimeLabel.Content = (maximum / maximum).ToString("P0", CultureInfo.InvariantCulture);
            }
            else
            {
                mainWindow.progressBar.Foreground = Brushes.Red;
                taskbar.SetProgressState(TaskbarProgressBarState.Error);
                mainWindow.startTimeLabel.Content = "FAIL";
            }
        }
    }
}
