using InABox.Clients;
using InABox.Core;
using JetBrains.Annotations;
using InABox.Avalonia.Platform;

namespace InABox.Avalonia
{
    public static class EntityDocumentUtils
    {
        [CanBeNull]
        public static T SaveDocument<T>(MobileDocument image, Func<T> shell, string auditmessage) where T : IEntityDocumentShell
        {
            T result = shell();
            if (result != null)
            {
                Document doc = new Document()
                {
                    FileName = image.FileName,
                    Data = image.Data,
                    CRC = CoreUtils.CalculateCRC(image.Data),
                    TimeStamp = DateTime.Now
                };
                new Client<Document>().Save(doc, auditmessage);


                result.DocumentID = doc.ID;
                result.FileName = doc.FileName;
                if ((!image.IsPDF()) && result.Thumbnail?.Any() != true)
                    result.Thumbnail = PlatformTools.ImageTools.CreateThumbnail(doc.Data, 256, 256);
                result.Save(auditmessage);
            }

            return result;
        }
    }
}