using System.IO;
using System.Windows.Media.Imaging;
using NexusShell.Models;

namespace NexusShell.Services;

public sealed class NexusMetadataService
{
    public NexusPhotoMetadata BuildMetadata(NexusPhotoItem? photo)
    {
        if (photo is null)
        {
            return new NexusPhotoMetadata
            {
                FileName = "—",
                SizeLabel = "—",
                CreatedLabel = "—",
                ModifiedLabel = "—",
                ResolutionLabel = "—",
                Format = "—",
                FolderLabel = "—",
                FullPath = "—",
                HasSelection = false,
            };
        }

        var resolution = photo.Width > 0 && photo.Height > 0
            ? $"{photo.Width} × {photo.Height}"
            : "Ukendt";

        return new NexusPhotoMetadata
        {
            FileName = photo.FileName,
            SizeLabel = NexusPhotosLibraryService.FormatBytes(photo.FileSizeBytes),
            CreatedLabel = NexusPhotosLibraryService.FormatDate(photo.CreatedUtc),
            ModifiedLabel = NexusPhotosLibraryService.FormatDate(photo.ModifiedUtc),
            ResolutionLabel = resolution,
            Format = photo.Format,
            FolderLabel = photo.FolderLabel,
            FullPath = photo.FullPath,
            HasSelection = true,
        };
    }

    public static (int Width, int Height) ReadDimensions(string filePath)
    {
        try
        {
            using var stream = File.OpenRead(filePath);
            var decoder = BitmapDecoder.Create(
                stream,
                BitmapCreateOptions.IgnoreColorProfile,
                BitmapCacheOption.OnLoad);
            var frame = decoder.Frames.FirstOrDefault();
            if (frame is null)
            {
                return (0, 0);
            }

            return (frame.PixelWidth, frame.PixelHeight);
        }
        catch
        {
            return (0, 0);
        }
    }
}
