using NLog;
using Prism.Mvvm;
using Prism.Navigation;
using Prism.Services;
using System.Threading.Tasks;

namespace Borepin.Base
{
    /// <summary>
    /// Base for all MVVM Based PageModels
    /// </summary>
    public abstract class PageModelBase : BindableBase, INavigationAware
    {
        #region Logger
        protected static readonly Logger Log = LogManager.GetCurrentClassLogger();
        #endregion

        #region Private Fields
        protected readonly INavigationService _NavigationService;
        protected readonly IPageDialogService _PageDialogService;

        protected PageModelBase(INavigationService navigationService, IPageDialogService pageDialogService)
        {
            _NavigationService = navigationService;
            _PageDialogService = pageDialogService;
        }
        #endregion

        #region Fields
        /// <summary>
        /// PageModel is Busy
        /// </summary>
        private bool _IsBusy = true;
        public bool IsBusy
        {
            get => _IsBusy;
            set => SetProperty(ref _IsBusy, value);
        }
        #endregion

        #region Mehtods
        public virtual Task LoadInstance(object instance)
        {
            return Task.CompletedTask;
        }

        public virtual Task LoadFromParameters(INavigationParameters parameters)
        {
            return Task.CompletedTask;
        }

        public virtual Task<object> CreateInstance()
        {
            return Task.FromResult<object>(null);
        }

        #endregion

        #region INavigationAware
        public async void OnNavigatedTo(INavigationParameters parameters)
        {
            await OnNavigatedToVirtual(parameters).ConfigureAwait(false);
            IsBusy = false;
        }
        public async void OnNavigatedFrom(INavigationParameters parameters)
        {
            await OnNavigatedFromVirtual(parameters).ConfigureAwait(false);
        }

        public virtual async Task OnNavigatedToVirtual(INavigationParameters parameters)
        {
            if (parameters.ContainsKey("instance"))
            {
                await LoadInstance(parameters.GetValue<object>("instance")).ConfigureAwait(false);
            }
            else
            {
                Log.Trace("No instance");
                await LoadInstance(null).ConfigureAwait(false);
            }

            await LoadFromParameters(parameters).ConfigureAwait(false);
        }
        public virtual async Task OnNavigatedFromVirtual(INavigationParameters parameters)
        {
            object instance = await CreateInstance().ConfigureAwait(false);
            if (instance != null)
            {
                parameters.Add("instance", instance);
            }
        }
        #endregion
    }
}