using Microsoft.Extensions.Logging;
using SteUp.Maui.Core.Utility;
using SteUp.Shared.Core.Dto;
using SteUp.Shared.Core.Helpers;
using SteUp.Shared.Core.Interface.System;

namespace SteUp.Maui.Core.Services;

public class AttachedService(ILogger<FileManager> logger) : IAttachedService
{
    public async Task<AttachedDto?> SelectImageFromCamera()
    {
        var cameraPerm = await Permissions.RequestAsync<Permissions.Camera>();
        var storagePerm = await Permissions.RequestAsync<Permissions.StorageWrite>();

        if (cameraPerm != PermissionStatus.Granted || storagePerm != PermissionStatus.Granted)
            return null;

        FileResult? result;

        try
        {
            result = await MediaPicker.Default.CapturePhotoAsync();
            result?.FileName = $"img_{DateTime.Now:ddMMyyy_hhmmss}{result.FileName[result.FileName.IndexOf('.')..]}";
        }
        catch (Exception ex)
        {
            logger.LogError(ex, ex.Message);
            Console.WriteLine($"Errore cattura foto: {ex.Message}");
            SentrySdk.CaptureException(ex);
            return null;
        }

        return result is null ? null : await UtilityFile.ConvertToDto(result, AttachedDto.TypeAttached.Image);
    }

    public async Task<List<AttachedDto>?> SelectImageFromGallery()
    {
        List<FileResult>? resultList;
        var storagePerm = await Permissions.RequestAsync<Permissions.StorageRead>();
        if (storagePerm != PermissionStatus.Granted)
            return null;

        try
        {
            resultList = await MediaPicker.Default.PickPhotosAsync();
        }
        catch (Exception ex)
        {
            logger.LogError(ex, ex.Message);
            Console.WriteLine($"Errore selezione galleria: {ex.Message}");
            SentrySdk.CaptureException(ex);
            return null;
        }

        if (resultList.IsNullOrEmpty()) return null;

        List<AttachedDto> returnList = [];
        foreach (var fileResult in resultList)
        {
            returnList.Add(await UtilityFile.ConvertToDto(fileResult, AttachedDto.TypeAttached.Image));
        }

        return returnList;
    }
}