using System;
using Avalonia.Interactivity;
using detect.gui.Classes;
using detect.gui.ViewModels;
using Avalonia;
using ReactiveUI;
using Avalonia.Controls.Primitives;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
using Avalonia.ReactiveUI;
using Avalonia.Threading;

namespace detect.gui.Views;

public partial class MainView : WindowBase<MainViewModel>
{
    public WebBrowserWindow WebWindow { get; set; }

    public MainView()
    {
        InitializeComponent();

        WebWindow = new WebBrowserWindow();

        var container = this.Get<RoutedViewHost>("RoutedViewHost");
        
        this.WhenAnyValue(x => x.ViewModel).Subscribe(v =>
        {
            if (v == null) return;
            v.WhenAnyValue(vd => vd.CurrentUser).Subscribe(u =>
            {
                if (u == null)
                {
                    Dispatcher.UIThread.InvokeAsync(() =>
                    {
                        WebWindow.Hide();
                    });
                    return;
                };
                Dispatcher.UIThread.InvokeAsync(() =>
                {
                    WebWindow.Width = container.Bounds.Width;
                    WebWindow.Height = container.Bounds.Height;
                    WebWindow.Position = container.PointToScreen(new Point(0, 0));
                    WebWindow.Show();
                });
            });
            v.Router.Navigate.Execute(new LoginViewModel());
        });

        this.WhenAnyValue(x => x.WindowState).Subscribe(s =>
        {
            Dispatcher.UIThread.InvokeAsync(() =>
            {
                if (s == WindowState.Minimized) 
                    WebWindow.Hide();
                if (s != WindowState.Minimized && (DataContext as MainViewModel)!.CurrentUser != null && !WebWindow.IsVisible)
                    WebWindow.Show();
            });
        });
    }

    private void InitializeComponent()
    {
        AvaloniaXamlLoader.Load(this);
#if DEBUG
        this.AttachDevTools();
#endif
    }

    protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
    {
        base.OnApplyTemplate(e);
        NotificationService.SetHostWindow(this);
    }

    private void MinClick(object? sender, RoutedEventArgs e)
    {
        WindowState = WindowState.Minimized;
    }

    private void MaxClick(object? sender, RoutedEventArgs e)
    {
        WindowState = WindowState.Maximized;
    }

    private void RestoreClick(object? sender, RoutedEventArgs e)
    {
        WindowState = WindowState.Normal;
    }

    private void CloseClick(object? sender, RoutedEventArgs e)
    {
        Close();
    }

    private void OnClosing(object? sender, WindowClosingEventArgs e)
    {
        WebWindow.Close();
    }
}
