using Borepin.Base;
using Borepin.Service;
using Borepin.Service.ErrorMessage;
using Borepin.Service.Storage;
using FabAccessAPI;
using FabAccessAPI.Exceptions;
using FabAccessAPI.Exceptions.SASL;
using Prism.AppModel;
using Prism.Navigation;
using Prism.Services;
using Prism.Services.Dialogs;
using System;
using System.Collections.Generic;
using System.Security.Authentication;
using Xamarin.Forms;

namespace Borepin.PageModel
{
    public class StartPageModel : ConnectionModelBase, IPageLifecycleAware
    {
        #region Private Fields
        private readonly ILoginStorageService _LoginStorageService;
        private readonly IErrorMessageService _ErrorMessageService;
        #endregion

        #region Constructors
        public StartPageModel(INavigationService navigationService, IPageDialogService pageDialogService, IAPIService apiService, ILoginStorageService loginStorageService, IErrorMessageService errorMessageService) : base(navigationService, pageDialogService, apiService)
        {
            _LoginStorageService = loginStorageService;
            _ErrorMessageService = errorMessageService;
        }
        #endregion

        #region Fields
        private bool _RunConnecting;
        public bool RunConnecting
        {
            get => _RunConnecting;
            set => SetProperty(ref _RunConnecting, value);
        }
        #endregion

        #region IPageLifecycleAware
        public async void OnAppearing()
        {
            IList<ConnectionData> connectionData_List = await _LoginStorageService.GetList().ConfigureAwait(false);
            ConnectionData connectionData_Default = await _LoginStorageService.GetDefault().ConfigureAwait(false);

            if (connectionData_List.Count == 0)
            {
                Device.BeginInvokeOnMainThread(async () =>
                {
                    INavigationResult result = await _NavigationService.NavigateAsync("/MainPage/NavigationPage/SetUpProcess_WelcomePage").ConfigureAwait(false);
                    if (result.Exception != null)
                    {
                        Log.Fatal(result.Exception, "Navigating failed");
                    }
                });
            }
            else if(connectionData_Default != null)
            {
                IsBusy = false;
                RunConnecting = true;
                try
                {
                    await _API.Connect(connectionData_Default).ConfigureAwait(false);
                    Device.BeginInvokeOnMainThread(async () =>
                    {
                        INavigationResult result = await _NavigationService.NavigateAsync("/MainPage/NavigationPage/MachineListPage").ConfigureAwait(false);
                        if (result.Exception != null)
                        {
                            Log.Fatal(result.Exception, "Navigating failed");
                        }
                    });
                }
                catch (Exception exception)
                {
                    _ErrorMessageService.DisplayConnectFailedMessage(exception);
                }

                if (_API.IsConnected == false)
                {
                    Device.BeginInvokeOnMainThread(async () =>
                    {
                        INavigationResult result = await _NavigationService.NavigateAsync("/MainPage/NavigationPage/ServerListPage").ConfigureAwait(false);
                        if (result.Exception != null)
                        {
                            Log.Fatal(result.Exception, "Navigating failed");
                        }
                    });
                }
            }
            else
            {
                Device.BeginInvokeOnMainThread(async () =>
                {
                    INavigationResult result = await _NavigationService.NavigateAsync("/MainPage/NavigationPage/ServerListPage").ConfigureAwait(false);
                    if (result.Exception != null)
                    {
                        Log.Fatal(result.Exception, "Navigating failed");
                    }
                });
            }
        }

        public void OnDisappearing()
        {
            
        }
        #endregion
    }
}
