using System;
using System.Threading;
using Cysharp.Threading.Tasks;
using Darkmatter.Core.Contracts.Services.Gallery;
using UnityEngine;

namespace Darkmatter.Services.Gallery
{
    public class GalleryService : IGalleryService
    {
        public async UniTask SaveImageAsync(Texture2D image, string fileName, CancellationToken cancellationToken)
        {
            var permission = await NativeGallery.RequestPermissionAsync(NativeGallery.PermissionType.Write,
                NativeGallery.MediaType.Image);

            if (permission != NativeGallery.Permission.Granted)
            {
                return;
            }

            var tcs = new UniTaskCompletionSource();
            var registration = cancellationToken.Register(() => tcs.TrySetCanceled(cancellationToken));

            NativeGallery.SaveImageToGallery(image, "Colorbook",
                filename: $"colorbook_{DateTime.UtcNow:yyyyMMdd_HHmmss}.png", callback: (success, path) =>
                {
                    registration.Dispose();
                    if (!success)
                    {
                        Debug.LogError("Failed to save image to gallery.");
                    }
                    else
                    {
                        Debug.Log($"Image saved to gallery at: {path}");
                    }

                    tcs.TrySetResult();
                });

            await tcs.Task;
        }
    }
}