using System.Drawing;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.Storage;
using Avalonia.Controls;
using Avalonia.Platform.Storage;
using InABox.Core;
using Microsoft.Maui.Media;


namespace InABox.Avalonia.Platform.Desktop;

public class Desktop_ImageTools : IImageTools
{
    public Logger? Logger { get; set; }
    
    // private static MediaCapture? _captureManager;
    //
    // private async Task<MediaCapture> InitMediaCapture()
    // {
    //     if (_captureManager == null)
    //     {
    //         _captureManager = new MediaCapture();
    //         MediaCaptureInitializationSettings _settings = new();
    //         await _captureManager.InitializeAsync(_settings);
    //     }
    //     return _captureManager;
    // }
    
    public byte[] CreateVideoThumbnail(byte[] video, int maxwidth, int maxheight)
    { 
        Logger?.Error("CreateVideoThumbnail() is not implemented on this platform");
        return video;
    }

    public byte[] CreateThumbnail(byte[] image, int maxwidth, int maxheight)
    { 
        Logger?.Error("CreateThumbnail() is not implemented on this platform");
        return image;
    }

    public async Task<ImageFile?> CapturePhotoAsync(TopLevel window, int? compression, Size? constraints)
    {
        // _captureManager = await InitMediaCapture();
        // var filename = $"{Path.GetFileNameWithoutExtension(Path.GetTempFileName())}.jpeg";
        // var location = await StorageFolder.GetFolderFromPathAsync(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures));
        // var storage = await location.CreateFileAsync(filename, CreationCollisionOption.GenerateUniqueName);
        // await _captureManager.CapturePhotoToStorageFileAsync(ImageEncodingProperties.CreateJpeg(), storage);
        // var data = await File.ReadAllBytesAsync(storage.Path);
        // var result = new ImageFile(storage.Name, data);
        // return result;
        
        // For the purposes of the desktop (demo) app, ignore the camera (above)
        // and always select a file
        return await PickPhotoAsync(window,compression,constraints);
    }
    
    public async Task<ImageFile?> PickPhotoAsync(TopLevel window, int? compression, Size? constraints) 
        => await PickMediaFile(window, "Select Image", WellKnownFolder.Pictures, [FilePickerFileTypes.ImageAll]);
    
    
    public async Task<ImageFile?> CaptureVideoAsync(TopLevel window)
    {
        return await PickVideoAsync(window);
    }

    private FilePickerFileType VideoFiles = new("Video File")
    {
        Patterns = ["*.mpeg", "*.avi", "*.mov", "*.mkv", "*mp4"],
        AppleUniformTypeIdentifiers = ["public.movie"],
        MimeTypes = ["video/mp4", "video/quicktime", "video/webm", "video/avi", "video/mpeg"]
    };
    
    public async Task<ImageFile?> PickVideoAsync(TopLevel window)
        => await PickMediaFile(window, "Select Video", WellKnownFolder.Videos, [VideoFiles]);
    
    private static async Task<ImageFile?> PickMediaFile(TopLevel window, string caption, WellKnownFolder folder, FilePickerFileType[] filters)
    {
        var startlocation = await window.StorageProvider.TryGetWellKnownFolderAsync(folder);
        var files = await window.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions()
        {
            Title = caption,
            FileTypeFilter = filters,
            AllowMultiple = false,
            SuggestedStartLocation = startlocation
        });
        var first = files.FirstOrDefault();
        if (first == null)
            return null;
        
        using var ms = new MemoryStream();
        await using var stream = await first.OpenReadAsync();
        await stream.CopyToAsync(ms);
        return new ImageFile(first.Name, ms.GetBuffer());
    }

    private async Task<ImageFile> ProcessFile(string filename, byte[]? data, int? compression, Size? constraints)
    {
        return new ImageFile(filename, data);
    }

    public byte[] RotateImage(byte[] image, float angle, int quality = 100)
    { 
        Logger?.Error("RotateImage() is not implemented on this platform");
        return image;
    }

    public byte[] ScaleImage(byte[] image, Size? constraints, int quality = 100)
    { 
        Logger?.Error("ScaleImage() is not implemented on this platform");
        return image;
    }
}