using System;
using System.Threading.Tasks;
using Xamarin.CommunityToolkit.Extensions;
using Xamarin.Essentials;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
using XamarinDemoApp.Views;
using XamarinDemoApp.Services;

namespace XamarinDemoApp
{
    public partial class App : Application
    {
        public Boolean HasStartedLocationMonitoring { get; set; }

        public App ()
        {
            InitializeComponent();

            MainPage = new AppShell();
            HasStartedLocationMonitoring = false;
        }

        protected async override void OnStart()
        {
            if (!HasStartedLocationMonitoring)
            {
                await CheckLocationPermissionAndStartLocationService();
            }
        }

        protected  override void OnResume()
        {
            Console.WriteLine("Test");
            //if (!HasStartedLocationMonitoring)
            //{
            //    await CheckLocationPermissionAndStartLocationService();
            //}
        }

        public async void GoToDetails(string loginId)
        {
            await Shell.Current.GoToAsync($"{nameof(DetailsPage)}?loginId={loginId}"); 
        }

        public async void GoToLogin()
        {
            await Shell.Current.GoToAsync("///LoginPage");
        }

        public void DisplayToastMsg(string msg)
        {
            MainPage.DisplayToastAsync(msg);
        }

        public async Task CheckLocationPermissionAndStartLocationService()
        {
            PermissionStatus status = await Permissions.CheckStatusAsync<Permissions.LocationAlways>();
            if (status == PermissionStatus.Denied && DeviceInfo.Platform == DevicePlatform.iOS)
            {
                return;
            }
            if (Permissions.ShouldShowRationale<Permissions.LocationAlways>())
            {
                await Shell.Current.DisplayAlert("Needs location permission",
                    "Location permission always is needed for enabling geofencing and bluetooth functionality. \nPlease go to app settings to set the permission."
                    , "OK");
                return;
            }

            status = await Permissions.RequestAsync<Permissions.LocationAlways>();

            if (status == PermissionStatus.Granted)
            {
                DependencyService.Get<ISDKBasicService>().StartMonitoringLocation();
                HasStartedLocationMonitoring = true;
            }
        }

        public void StopLocationMonitoring()
        {
            if (!HasStartedLocationMonitoring)
            {
                return;
            }
            DependencyService.Get<ISDKBasicService>().DisableLocationMonitoring();
            HasStartedLocationMonitoring = false;
        }

    }
}

