using Borepin.Service.BFFH; using Borepin.Service.BFFH.Exceptions; using Prism.Navigation; using Prism.Services; using System.Threading.Tasks; using Xamarin.Forms; namespace Borepin.Base { /// /// Base for all BFFH Based PageModels /// public abstract class ConnectionModelBase : PageModelBase { #region Private Fields protected readonly IPageDialogService _PageDialogService; protected readonly IBFFHService _BFFHService; #endregion #region Constructors protected ConnectionModelBase(INavigationService navigationService, IPageDialogService pageDialogService, IBFFHService bFFHService) : base(navigationService) { _PageDialogService = pageDialogService; _BFFHService = bFFHService; } #endregion #region Fields /// /// PageModel is Connected /// private bool _IsConnected = true; public bool IsConnected { get => _IsConnected; set => SetProperty(ref _IsConnected, value); } #endregion #region Methods /// /// Checks connection to Server. /// Display message if Connection is lost. /// /// True if connection is ok. public async Task CheckConnection() { try { if(_BFFHService.CurrentConnection != null && !_BFFHService.IsConnected) { await _BFFHService.Reconnect().ConfigureAwait(false); } else if(_BFFHService.CurrentConnection == null) { return false; } return true; } catch (ReconnectingFailedException) { Device.BeginInvokeOnMainThread(async () => { await _PageDialogService.DisplayAlertAsync("Connection failed", "Lost connection to server.", "Ok").ConfigureAwait(false); }); IsConnected = false; return false; } } #endregion } }