using FluentResults;
using Result = FluentResults.Result;
using Microsoft.Maui.Devices;
using NexusReader.Application.Abstractions.Services;

namespace NexusReader.Infrastructure.Mobile.Services;

public sealed class MauiPlatformService : IPlatformService
{
    public async Task<Result> VibrateSuccessAsync()
    {
        try 
        {
            HapticFeedback.Default.Perform(HapticFeedbackType.Click);
            await Task.Delay(100);
            HapticFeedback.Default.Perform(HapticFeedbackType.Click);
            return Result.Ok();
        }
        catch (Exception ex)
        {
            return Result.Fail(ex.Message);
        }
    }

    public async Task<Result> VibrateErrorAsync()
    {
        try 
        {
            HapticFeedback.Default.Perform(HapticFeedbackType.LongPress);
            return Result.Ok();
        }
        catch (Exception ex)
        {
            return Result.Fail(ex.Message);
        }
    }

    public async Task<Result> VibrateAsync(int milliseconds)
    {
        try 
        {
            HapticFeedback.Default.Perform(HapticFeedbackType.Click);
            return Result.Ok();
        }
        catch (Exception ex)
        {
            return Result.Fail(ex.Message);
        }
    }

    public Result<DeviceContext> GetDeviceContext()
    {
        try 
        {
            var device = DeviceInfo.Current;
            var display = DeviceDisplay.Current.MainDisplayInfo;

            return Result.Ok(new DeviceContext(
                device.Model,
                device.Manufacturer,
                MapDeviceType(device.Idiom),
                MapOrientation(display.Orientation)
            ));
        }
        catch (Exception ex)
        {
            return Result.Fail(ex.Message);
        }
    }

    private static NexusReader.Application.Abstractions.Services.DeviceType MapDeviceType(DeviceIdiom idiom)
    {
        if (idiom == DeviceIdiom.Phone) return NexusReader.Application.Abstractions.Services.DeviceType.Phone;
        if (idiom == DeviceIdiom.Tablet) return NexusReader.Application.Abstractions.Services.DeviceType.Tablet;
        if (idiom == DeviceIdiom.Desktop) return NexusReader.Application.Abstractions.Services.DeviceType.Desktop;
        return NexusReader.Application.Abstractions.Services.DeviceType.Unknown;
    }

    private static NexusReader.Application.Abstractions.Services.DisplayOrientation MapOrientation(Microsoft.Maui.Devices.DisplayOrientation orientation) => orientation switch
    {
        Microsoft.Maui.Devices.DisplayOrientation.Portrait => NexusReader.Application.Abstractions.Services.DisplayOrientation.Portrait,
        Microsoft.Maui.Devices.DisplayOrientation.Landscape => NexusReader.Application.Abstractions.Services.DisplayOrientation.Landscape,
        _ => NexusReader.Application.Abstractions.Services.DisplayOrientation.Unknown
    };
}
