using Android.App;
using Android.Content;
using Android.OS;
using Android.Provider;
using salesbook.Shared.Core.Interface.System.Battery;
using Application = Android.App.Application;

namespace salesbook.Maui.Core;

public class BatteryOptimizationManagerService : IBatteryOptimizationManagerService
{
    public bool IsBatteryOptimizationEnabled()
    {
        var packageName = AppInfo.PackageName;
        
        var pm = (PowerManager)Application.Context.GetSystemService(Context.PowerService)!;
        return !pm.IsIgnoringBatteryOptimizations(packageName);
    }

    public void OpenBatteryOptimizationSettings(Action<bool> onCompleted)
    {
        var packageName = AppInfo.PackageName;

        var intent = new Intent(Settings.ActionRequestIgnoreBatteryOptimizations);
        intent.SetData(Android.Net.Uri.Parse("package:" + packageName));
        ((MainActivity)Platform.CurrentActivity!).StartActivityForResult(intent, (result, _) => { onCompleted(result == Result.Ok); });
    }
}