using KioskApp.Portal.Platforms.Attributes;
using KioskApp.Portal.Widgets;
using Microsoft.Web.WebView2.Core;

namespace KioskApp.Portal.Platforms.Windows.Widgets;

[SupportedOS(SupportedOS.Windows)]
public class WebView : BaseWebView
{
    private string _lastUrl = string.Empty;
    private CoreWebView2Controller? _controller;
    
    
    protected override void InternalCreate()
    {
        InternalCreateAsync();
        return;

        async void InternalCreateAsync()
        {
            var window = GetParentWindow();
            var env = await CoreWebView2Environment.CreateAsync();
            _controller = await env.CreateCoreWebView2ControllerAsync(window.GetNativeHandle());
       
            var clientSize = GetParentWindow().GetClientSize();
            _controller.Bounds = new(0, 0, (int)clientSize.Width, (int)clientSize.Height);
        
            if (!string.IsNullOrEmpty(_lastUrl))
            {
                _controller.CoreWebView2.Navigate(_lastUrl);
                _lastUrl = string.Empty;
            }
        }
    }

    public override void Resize(int width, int height)
    {
        _controller.Bounds = new(0, 0, width, height);
    }

    public override void Navigate(string url)
    {
        if (_controller == null)
        {
            _lastUrl = url;
            return;
        }
        _controller.CoreWebView2.Navigate(url);
    }

    public override void Dispose()
    {
       _controller.Close();
    }
}