using AnotherReplayReader.Utils;
using System.Diagnostics;
using System.Linq;
using System.Windows;
using System.Windows.Documents;

namespace AnotherReplayReader
{
    /// <summary>
    /// About.xaml 的交互逻辑
    /// </summary>
    internal partial class About : Window
    {
        private readonly Cache _cache;
        private readonly UpdateCheckerVersionData? _updateData;

        public About(Cache cache)
        {
            _cache = cache;
            InitializeComponent();
        }

        public About(Cache cache, UpdateCheckerVersionData updateData)
        {
            _cache = cache;
            _updateData = updateData;
            InitializeComponent();
        }

        private async void OnAboutWindowLoaded(object sender, RoutedEventArgs e)
        {
            foreach (var hyperlink in this.FindVisualChildren<Hyperlink>())
            {
                hyperlink.RequestNavigate += OnHyperlinkRequestNavigate;
            }

            await _cache.Initialization;
            _checkForUpdates.IsChecked = _cache.GetOrDefault(UpdateChecker.CheckForUpdatesKey, false);
            var data = _updateData
                ?? _cache.GetOrDefault<UpdateCheckerVersionData?>(UpdateChecker.CachedDataKey, null);
            if (data is { } updateData && updateData.IsNewVersion())
            {
                _updatePanel.Visibility = Visibility.Visible;
                _updateInfo.Inlines.Add(updateData.Description);
                _updateInfo.Inlines.Add(new LineBreak());
                updateData.Urls.Select(u =>
                {
                    var h = new Hyperlink();
                    h.Inlines.Add(u);
                    h.NavigateUri = new(u);
                    h.RequestNavigate += OnHyperlinkRequestNavigate;
                    return h;
                });
            }

            _ = Auth.Id.ContinueWith(t => Dispatcher.Invoke(() =>
            {
                if (t.Result is { } id)
                {
                    _idBox.Text = id;
                }
                else
                {
                    _bottom.Visibility = Visibility.Collapsed;
                }
            }));
        }

        private void OnHyperlinkRequestNavigate(object sender, System.Windows.Navigation.RequestNavigateEventArgs e)
        {
            Process.Start(e.Uri.ToString());
        }

        private async void OnCheckForUpdatesCheckedChanged(object sender, RoutedEventArgs e)
        {
            _cache.Set(UpdateChecker.CheckForUpdatesKey, _checkForUpdates.IsChecked is true);
            await _cache.Save();
        }
    }
}