using salesbook.Shared.Core.Dto;
using salesbook.Shared.Core.Interface;

namespace salesbook.Maui.Core.Services;

public class AttachedService : IAttachedService
{
    public async Task<AttachedDTO?> SelectImage()
    {
        var perm = await Permissions.RequestAsync<Permissions.Photos>();
        if (perm != PermissionStatus.Granted) return null;

        var result = await FilePicker.PickAsync(new PickOptions
        {
            PickerTitle = "Scegli un'immagine",
            FileTypes = FilePickerFileType.Images
        });

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

    public async Task<AttachedDTO?> SelectFile()
    {
        var perm = await Permissions.RequestAsync<Permissions.StorageRead>();
        if (perm != PermissionStatus.Granted) return null;

        var result = await FilePicker.PickAsync();

        return result is null ? null : await ConvertToDto(result, AttachedDTO.TypeAttached.Document);
    }

    public async Task<AttachedDTO?> SelectPosition()
    {
        var perm = await Permissions.RequestAsync<Permissions.LocationWhenInUse>();
        if (perm != PermissionStatus.Granted) return null;

        var loc = await Geolocation.GetLastKnownLocationAsync();
        if (loc is null) return null;

        return new AttachedDTO
        {
            Name = "Posizione attuale",
            Lat = loc.Latitude,
            Lng = loc.Longitude,
            Type = AttachedDTO.TypeAttached.Position
        };
    }

    private static async Task<AttachedDTO> ConvertToDto(FileResult file, AttachedDTO.TypeAttached type)
    {
        var stream = await file.OpenReadAsync();
        using var ms = new MemoryStream();
        await stream.CopyToAsync(ms);

        return new AttachedDTO
        {
            Name = file.FileName,
            Path = file.FullPath,
            MimeType = file.ContentType,
            DimensionBytes= ms.Length,
            FileContent = ms.ToArray(),
            Type = type
        };
    }
}