using System;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Windows.Input;
using Katteker;
using MaterialDesignThemes.Wpf;
using Prism.Commands;
using Prism.Mvvm;

namespace ExampleCore
{
    [JetBrains.Annotations.UsedImplicitly]
    public class MainWindowViewModel : BindableBase, IDisposable
    {
        private bool _showRestartAppDialog;
        private readonly UpdateManager _updateManager;

        public MainWindowViewModel()
        {

            UpdateManager.TryCreate(out _updateManager);
            UpdateCommand = new DelegateCommand<string>(async x => await UpdateAsync(x).ConfigureAwait(false));
            RestartAppDialogCommand = new DelegateCommand<object>(RestartApp);
            OpenFileDialogCommand = new DelegateCommand(OpenFileCommand);
        }

        private void OpenFileCommand()
        {
            var openFile = new FolderBrowserDialog();
            if (openFile.ShowDialog() == DialogResult.OK)
            {
                MessageBox.Show(openFile.SelectedPath, "Example Core");
            }
        }

        private void RestartApp(object obj)
        {
            if (obj is bool restart && restart)
            {
                _updateManager.RestartApp();
            }

            ShowRestartAppDialog = false;
        }

        private async Task UpdateAsync(string startup)
        {
            if (_updateManager == null) return;
            var silent = bool.Parse(startup);
            try
            {
                var releases = (await _updateManager.CheckForUpdateAsync().ConfigureAwait(false)).ToList();
                if (releases.Any())
                {
                    MessageQueue.Enqueue("Update available", "Update now", ActionHandler);
                }
                else if (!silent)
                {
                    MessageQueue.Enqueue("No Update available.", true);
                }
            }
            catch (Exception e)
            {
                if (silent)
                {
                    MessageQueue.Enqueue(e.Message);
                }
            }
        }

        private async void ActionHandler()
        {
            if (await _updateManager.UpdateAppAsync().ConfigureAwait(false))
            {
                ShowRestartAppDialog = true;
            }
        }

        public ICommand UpdateCommand { get; }

        public SnackbarMessageQueue MessageQueue { get; } = new SnackbarMessageQueue();

        public bool ShowRestartAppDialog
        {
            get => _showRestartAppDialog;
            set => SetProperty(ref _showRestartAppDialog, value);
        }

        public ICommand RestartAppDialogCommand { get; }

        public ICommand OpenFileDialogCommand
        {
            get;
        }

        public void Dispose()
        {
            MessageQueue?.Dispose();
        }
    }
}