<commit_before>﻿using ContosoMoments.Views;
using Microsoft.WindowsAzure.MobileServices;
using Microsoft.WindowsAzure.MobileServices.Eventing;
using Microsoft.WindowsAzure.MobileServices.Files;
using Microsoft.WindowsAzure.MobileServices.SQLiteStore;
using Microsoft.WindowsAzure.MobileServices.Sync;
using PCLStorage;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace ContosoMoments
{
    public class App : Application
    {
        private string ApplicationURL = @"https://donnamcontosomoments.azurewebsites.net";

        //public static string DB_LOCAL_FILENAME = "localDb-" + DateTime.Now.Ticks + ".sqlite";
        public const string LocalDbFilename = "localDb.sqlite";
        public MobileServiceClient MobileService;
        public MobileServiceUser AuthenticatedUser;

        public IMobileServiceSyncTable<Models.Album> albumTableSync;
        public IMobileServiceSyncTable<Models.Image> imageTableSync;
        public IMobileServiceSyncTable<ResizeRequest> resizeRequestSync;

        public static App Instance;
        public static object UIContext { get; set; }

        private static Object currentDownloadTaskLock = new Object();
        private static Task currentDownloadTask = Task.FromResult(0);

        public string DataFilesPath { get; set; }

        private string currentUserId;

        public string CurrentUserId
        {
            get { return currentUserId ?? Settings.Current.DefaultUserId; }
            set {
                currentUserId = value;
                Settings.Current.CurrentUserId = currentUserId;
            }
        }

        public App()
        {
            Instance = this;

            Label label = new Label() { Text = "Loading..." };
            label.TextColor = Color.White;
            Image img = new Image() { Source = ImageSource.FromFile("logo.png") };
            StackLayout stack = new StackLayout();
            stack.VerticalOptions = LayoutOptions.Center;
            stack.HorizontalOptions = LayoutOptions.Center;
            stack.Orientation = StackOrientation.Vertical;
            stack.Children.Add(img);
            stack.Children.Add(label);
            ContentPage page = new ContentPage();
            page.BackgroundColor = Color.FromHex("#8C0A4B");
            page.Content = stack;
            MainPage = page;
        }

        protected override async void OnStart()
        {
            if (Settings.Current.MobileAppUrl == Settings.DefaultMobileAppUrl) {
                MainPage = new SettingsView(this);
            }
            else {
                await InitMobileService(Settings.Current.MobileAppUrl);
            }
        }

        internal async Task InitMobileService(string uri, bool firstStart = false)
        {
            this.ApplicationURL = uri;

            var authHandler = new AuthHandler();
            MobileService = new MobileServiceClient(ApplicationURL, new LoggingHandler(true), authHandler);
            authHandler.Client = MobileService;
            AuthenticatedUser = MobileService.CurrentUser;

            await InitLocalStoreAsync(LocalDbFilename);
            InitLocalTables();

            IPlatform platform = DependencyService.Get<IPlatform>();
            DataFilesPath = await platform.GetDataFilesPath();

#if __DROID__ && PUSH
            Droid.GcmService.RegisterWithMobilePushNotifications();
#elif __IOS__ && PUSH
           iOS.AppDelegate.IsAfterLogin = true;
           await iOS.AppDelegate.RegisterWithMobilePushNotifications();
#elif __WP__ && PUSH
           ContosoMoments.WinPhone.App.AcquirePushChannel(App.Instance.MobileService);
#endif

            if (firstStart) {
                await Utils.PopulateDefaultsAsync();

                var loginPage = new Login();
                MainPage = new NavigationPage(new AlbumsListView(this));

                await MainPage.Navigation.PushAsync(loginPage);
                await loginPage.GetResultAsync();
            }
            else {
                currentUserId = Settings.Current.CurrentUserId;
                MainPage = new NavigationPage(new AlbumsListView(this));
            }
        }

        internal async Task ResetAsync(string uri)
        {
            var platform = DependencyService.Get<IPlatform>();
            MobileService.Dispose();

            string path = Path.Combine(platform.GetRootDataPath(), LocalDbFilename);
            await FileHelper.DeleteLocalFileAsync(path);

            await InitMobileService(uri, firstStart: true);
            }

        internal async Task LogoutAsync()
        {
            await MobileService.LogoutAsync();

            await imageTableSync.PurgeAsync("allImages", imageTableSync.CreateQuery(), CancellationToken.None);
            await albumTableSync.PurgeAsync("allAlbums", imageTableSync.CreateQuery(), CancellationToken.None);
            await resizeRequestSync.PurgeAsync(true);

            var albumListView = new AlbumsListView(this);
            MainPage = new NavigationPage(albumListView);

            var loginPage = new Login();           
            await MainPage.Navigation.PushAsync(loginPage);
            await loginPage.GetResultAsync();

            albumListView.OnRefresh(albumListView, EventArgs.Empty); // reload data, since now the user might be logged in
        }

        public async Task InitLocalStoreAsync(string localDbFilename)
        {
            if (!MobileService.SyncContext.IsInitialized) {
                var store = new MobileServiceSQLiteStore(localDbFilename);
                store.DefineTable<Models.Album>();
                store.DefineTable<Models.Image>();
                store.DefineTable<ResizeRequest>();

                // Initialize file sync
                MobileService.InitializeFileSyncContext(new FileSyncHandler(this), store, new FileSyncTriggerFactory(MobileService, true));

                // Uses the default conflict handler, which fails on conflict
                await MobileService.SyncContext.InitializeAsync(store, StoreTrackingOptions.NotifyLocalAndServerOperations);
            }
        }

        public async Task SyncAlbumsAsync()<commit_msg>Mobile client: fix logout bug<commit_after>﻿using ContosoMoments.Views;
using Microsoft.WindowsAzure.MobileServices;
using Microsoft.WindowsAzure.MobileServices.Eventing;
using Microsoft.WindowsAzure.MobileServices.Files;
using Microsoft.WindowsAzure.MobileServices.SQLiteStore;
using Microsoft.WindowsAzure.MobileServices.Sync;
using PCLStorage;
using System;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace ContosoMoments
{
    public class App : Application
    {
        private string ApplicationURL = @"https://donnamcontosomoments.azurewebsites.net";

        //public static string DB_LOCAL_FILENAME = "localDb-" + DateTime.Now.Ticks + ".sqlite";
        public const string LocalDbFilename = "localDb.sqlite";
        public MobileServiceClient MobileService;
        public MobileServiceUser AuthenticatedUser;

        public IMobileServiceSyncTable<Models.Album> albumTableSync;
        public IMobileServiceSyncTable<Models.Image> imageTableSync;
        public IMobileServiceSyncTable<ResizeRequest> resizeRequestSync;

        public static App Instance;
        public static object UIContext { get; set; }

        private static Object currentDownloadTaskLock = new Object();
        private static Task currentDownloadTask = Task.FromResult(0);

        public string DataFilesPath { get; set; }

        private string currentUserId;

        public string CurrentUserId
        {
            get { return currentUserId ?? Settings.Current.DefaultUserId; }
            set {
                currentUserId = value;
                Settings.Current.CurrentUserId = currentUserId;
            }
        }

        public App()
        {
            Instance = this;

            Label label = new Label() { Text = "Loading..." };
            label.TextColor = Color.White;
            Image img = new Image() { Source = ImageSource.FromFile("logo.png") };
            StackLayout stack = new StackLayout();
            stack.VerticalOptions = LayoutOptions.Center;
            stack.HorizontalOptions = LayoutOptions.Center;
            stack.Orientation = StackOrientation.Vertical;
            stack.Children.Add(img);
            stack.Children.Add(label);
            ContentPage page = new ContentPage();
            page.BackgroundColor = Color.FromHex("#8C0A4B");
            page.Content = stack;
            MainPage = page;
        }

        protected override async void OnStart()
        {
            if (Settings.Current.MobileAppUrl == Settings.DefaultMobileAppUrl) {
                MainPage = new SettingsView(this);
            }
            else {
                await InitMobileService(Settings.Current.MobileAppUrl);
            }
        }

        internal async Task InitMobileService(string uri, bool firstStart = false)
        {
            this.ApplicationURL = uri;

            var authHandler = new AuthHandler();
            MobileService = new MobileServiceClient(ApplicationURL, new LoggingHandler(true), authHandler);
            authHandler.Client = MobileService;
            AuthenticatedUser = MobileService.CurrentUser;

            await InitLocalStoreAsync(LocalDbFilename);
            InitLocalTables();

            IPlatform platform = DependencyService.Get<IPlatform>();
            DataFilesPath = await platform.GetDataFilesPath();

#if __DROID__ && PUSH
            Droid.GcmService.RegisterWithMobilePushNotifications();
#elif __IOS__ && PUSH
           iOS.AppDelegate.IsAfterLogin = true;
           await iOS.AppDelegate.RegisterWithMobilePushNotifications();
#elif __WP__ && PUSH
           ContosoMoments.WinPhone.App.AcquirePushChannel(App.Instance.MobileService);
#endif

            if (firstStart) {
                await Utils.PopulateDefaultsAsync();

                var loginPage = new Login();
                MainPage = new NavigationPage(new AlbumsListView(this));

                await MainPage.Navigation.PushAsync(loginPage);
                await loginPage.GetResultAsync();
            }
            else {
                currentUserId = Settings.Current.CurrentUserId;
                MainPage = new NavigationPage(new AlbumsListView(this));
            }
        }

        internal async Task ResetAsync(string uri)
        {
            var platform = DependencyService.Get<IPlatform>();
            MobileService.Dispose();

            string path = Path.Combine(platform.GetRootDataPath(), LocalDbFilename);
            await FileHelper.DeleteLocalFileAsync(path);

            await InitMobileService(uri, firstStart: true);
            }

        internal async Task LogoutAsync()
        {
            await MobileService.LogoutAsync();

            await imageTableSync.PurgeAsync("allImages", null, true, CancellationToken.None);
            await albumTableSync.PurgeAsync("allAlbums", null, true, CancellationToken.None);
            await resizeRequestSync.PurgeAsync(true);

            currentUserId = null;
            Settings.Current.AuthenticationType = Settings.AuthOption.GuestAccess;

            var albumListView = new AlbumsListView(this);
            MainPage = new NavigationPage(albumListView);

            var loginPage = new Login();           
            await MainPage.Navigation.PushAsync(loginPage);
            await loginPage.GetResultAsync();

            albumListView.OnRefresh(albumListView, EventArgs.Empty); // reload data, since now the user might be logged in
        }

        public async Task InitLocalStoreAsync(string localDbFilename)
        {
            if (!MobileService.SyncContext.IsInitialized) {
                var store = new MobileServiceSQLiteStore(localDbFilename);
                store.DefineTable<Models.Album>();
                store.DefineTable<Models.Image>();
                store.DefineTable<ResizeRequest>();

                // Initialize file sync
                MobileService.InitializeFileSyncContext(new FileSyncHandler(this), store, new FileSyncTriggerFactory(MobileService, true));

                // Uses the default conflict handler, which fails on conflict
                await MobileService.SyncContext.InitializeAsync(store, StoreTrackingOptions.NotifyLocalAndServerOperations);
            }
        }

        public async Task SyncAlbumsAsync()
{'fraction_non_alphanumeric': 0.07971592722630066, 'fraction_numerical': 0.0006383657835939994, 'mean_word_length': 2.3618562231759657, 'pattern_counts': {'":': 0, '<': 19, '<?xml version=': 0, '>': 19, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 4, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3606972', 'n_tokens_mistral': 3043, 'n_tokens_neox': 2963, 'n_words': 671}