using System;
using System.Threading.Tasks;
using Flashcard.ViewModels;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;

namespace Flashcard {
    partial class App {
        public App() {
            InitializeComponent();
        }

        protected async override void OnLaunched(LaunchActivatedEventArgs args) {
            App.Current.Resources["MainViewModelDataSource"] = new MainViewModel();

            if (args.PreviousExecutionState == ApplicationExecutionState.Terminated) {
                await this.RestoreSettings();
            }

            this.Suspending += App_Suspending;
            this.Resuming += App_Resuming;
            this.Exiting += App_Exiting;

            Window.Current.Content = new Views.MainPage();
            Window.Current.Activate();
        }

        private async void App_Resuming(object sender, object e) {
            await RestoreSettings();
        }

        private async Task RestoreSettings() {
            await SuspensionManager.RestoreAsync();
            object value;
            if (SuspensionManager.SessionState.TryGetValue("Question", out value)) {
                this.ViewModel.Question = value as Models.Question;
            }
        }

        private async void App_Exiting(object sender, object e) {
            await SaveSettings();
        }

        private async void App_Suspending(object sender, Windows.ApplicationModel.SuspendingEventArgs e) {
            await SaveSettings();
            e.SuspendingOperation.GetDeferral().Complete();
        }

        private async Task SaveSettings() {
            SuspensionManager.SessionState["Question"] = this.ViewModel.Question;
            await SuspensionManager.SaveAsync();
        }


        private MainViewModel ViewModel {
            get { return this.Resources["MainViewModelDataSource"] as MainViewModel; }
        }


    }
}
