using InABox.Clients;
using InABox.Core;
using InABox.WPF;
using Org.BouncyCastle.Crmf;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Media.Imaging;

namespace InABox.DynamicGrid;

public class DFImageControl : DynamicFormControl<DFLayoutImage>
{
    private static readonly Dictionary<Guid, BitmapImage?> images = new();
    protected override FrameworkElement Create()
    {
        var image = new Image();
        if (Control.Image.IsValid())
        {
            if (images.TryGetValue(Control.Image.ID, out var bitmapImage))
            {
                image.Source = bitmapImage;
            }
            new Client<Document>().Query(
                new Filter<Document>(x => x.ID).IsEqualTo(Control.Image.ID),
                Columns.None<Document>().Add(x => x.ID, x => x.Data),
                null,
                null,
                (data, error) =>
                {
                    var source = ImageUtils.LoadImage(data?.Rows.FirstOrDefault()?.Get<Document, byte[]>(x => x.Data));
                    images[Control.Image.ID] = source;
                    Dispatcher.Invoke(() => { image.Source = source; });
                }
            );
        }

        image.Stretch = Stretch.Uniform;
        return image;
    }
}
