using C1.Xaml.Excel;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.System;
using Windows.UI.Core;
using Windows.UI.Popups;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace ControlExplorer
{
    public sealed partial class OneDriveExplorer : UserControl
    {
        public OneDriveExplorer(string accessToken)
        {
            this.InitializeComponent();
            AccessToken = accessToken;
        }

        //private Action<C1XLBook> createBookActionSaved;
        //private string fileNameSaved;
        private string AccessToken { get; set; }
        private TaskCompletionSource<OneDriveFolder> _getFolderCompletionSource;

        public async Task<OneDriveFolder> GetOneDriveFolderAsync()
        {
            var statusBar = StatusBar.GetForCurrentView();
            _getFolderCompletionSource = new TaskCompletionSource<OneDriveFolder>();
            statusBar.ProgressIndicator.Text = "Getting folders from OneDrive...";
            await statusBar.ProgressIndicator.ShowAsync();
            try
            {

                var folders = await OneDriveHelper.GetFoldersAsync(AccessToken);
                await statusBar.ProgressIndicator.HideAsync();
                if (folders.Count == 0)
                {
                    var dialog = new MessageDialog("You should have at least a folder to upload the document to.");
                    await dialog.ShowAsync();
                    _getFolderCompletionSource.TrySetCanceled();
                }
                else
                {
                    foldersList.ItemsSource = folders;
                    selectFolder.Visibility = Visibility.Visible;
                }
            }
            catch(Exception exc)
            {
                _getFolderCompletionSource.TrySetException(exc);
            }
            return await _getFolderCompletionSource.Task;
        }

        private async void foldersList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var selFolder = foldersList.SelectedItem as OneDriveFolder;
            if (selFolder != null)
            {
                selectFolder.Visibility = Visibility.Collapsed;
                _getFolderCompletionSource.TrySetResult(selFolder);
            }
        }

        private void foldersList_ContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args)
        {

        }
    }
}
