using Scry.ViewModels;

namespace Scry.Views;

public partial class ScanPage : ContentPage
{
    public ScanPage(ScanViewModel viewModel)
    {
        InitializeComponent();
        BindingContext = viewModel;
    }

    protected override async void OnAppearing()
    {
        base.OnAppearing();

        // Request camera permission
        var status = await Permissions.CheckStatusAsync<Permissions.Camera>();
        if (status != PermissionStatus.Granted)
        {
            status = await Permissions.RequestAsync<Permissions.Camera>();
            if (status != PermissionStatus.Granted)
            {
                await DisplayAlertAsync("Permission Denied", "Camera permission is required to scan cards.", "OK");
                return;
            }
        }

        // Start camera when page appears
        try
        {
            await cameraView.StartCameraPreview(CancellationToken.None);
        }
        catch (Exception ex)
        {
            await DisplayAlertAsync("Camera Error", $"Could not start camera: {ex.Message}", "OK");
        }
    }

    protected override void OnDisappearing()
    {
        base.OnDisappearing();

        // Stop camera when leaving page
        try
        {
            cameraView.StopCameraPreview();
        }
        catch
        {
            // Ignore cleanup errors
        }
    }
}
