using System;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Markup.Xaml;
using Avalonia.Platform;
using detect.gui.Services;
using detect.gui.Views;
using detect.gui.VWMS;
using Serilog;
using Splat;
using WebViewControl;

namespace detect.gui.VWS;

public partial class MainWindow : Window
{
    private static MainWindow? _instance;

    public static MainWindow Instance()
    {
        return _instance ??= new MainWindow();
    }

    public MainWindow()
    {
        InitializeComponent();

        Icon = new WindowIcon(AssetLoader.Open(new Uri("avares://detect.gui/Assets/logo.ico")));
        Title = "AI智能视频分析平台";
        ExtendClientAreaToDecorationsHint = true;
        ExtendClientAreaChromeHints = ExtendClientAreaChromeHints.NoChrome;
        ExtendClientAreaTitleBarHeightHint = -1;
        SystemDecorations = SystemDecorations.None;
        Topmost = false;
        CanResize = false;

        if (Screens.Primary == null) return;
        Width = Screens.Primary.Bounds.Width / Screens.Primary.Scaling;
        Height = Screens.Primary.Bounds.Height / Screens.Primary.Scaling;
        Position = new PixelPoint(0, 0);
        DataContext = Locator.Current.GetService<MainWindowModel>();

        var webview = this.Get<WebView>("WebView");
        var service = Locator.Current.GetService<DeviceClientService>();
        webview.RegisterJavascriptObject("DeviceClientService", service);
        webview.RegisterJavascriptObject("WebViewService", new WebViewService(this));
        webview.RegisterJavascriptObject("OCRService", new OCRService());
        Log.Information("WebView Initialized.");
    }

    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)
    {
        this.Get<WebView>("WebView").Dispose();
        Locator.Current.GetService<NotificationWindow>()!.Close();
    }
}