using System;
using System.Threading.Tasks;
using Windows.Foundation;
using Windows.Graphics.Printing;
using Windows.Graphics.Printing.OptionDetails;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.Storage;
using Windows.System;
using Prism.Windows.Mvvm;
using FooEditEngine.UWP;
using FooEditor.UWP.ViewModels;
using FooEditor.UWP.Models;
using Windows.UI.Xaml.Navigation;

namespace FooEditor.UWP.Views
{
    public sealed partial class MainPage : SessionStateAwarePage
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        void MainPage_PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
        {
            IAsyncAction async = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                MainPageViewModel vm = this.DataContext as MainPageViewModel;
                var source = vm.CurrentDocument.CreatePrintDocument();
                PrintTask task = null;
                task = args.Request.CreatePrintTask(vm.CurrentDocument.Title, (e) =>
                {
                    e.SetSource(source);
                });
                task.Completed += (s, e) => {
                    source.Dispose();
                    System.Diagnostics.Debug.WriteLine("finshed printing");
                };
                PrintOptionBuilder<DocumentSource> builder = new PrintOptionBuilder<DocumentSource>(source);
                builder.BuildPrintOption(PrintTaskOptionDetails.GetFromPrintTaskOptions(task.Options));
            });
            Task t = WindowsRuntimeSystemExtensions.AsTask(async);
            t.Wait();
        }

        protected override void OnNavigatedFrom(NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            PrintManager.GetForCurrentView().PrintTaskRequested -= MainPage_PrintTaskRequested;
            Window.Current.CoreWindow.KeyUp -= CoreWindow_KeyUp;
        }

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            base.OnNavigatedTo(e);
            //VM内で追加する設定が反映されないので、ここで追加する
            MainPageViewModel vm = this.DataContext as MainPageViewModel;
            PrintManager.GetForCurrentView().PrintTaskRequested += MainPage_PrintTaskRequested;
            Window.Current.CoreWindow.KeyUp += CoreWindow_KeyUp;
        }

        bool IsModiferKeyPressed(VirtualKey key)
        {
            CoreVirtualKeyStates state = Window.Current.CoreWindow.GetKeyState(key);
            return (state & CoreVirtualKeyStates.Down) == CoreVirtualKeyStates.Down;
        }

        void CoreWindow_KeyUp(CoreWindow sender, KeyEventArgs e)
        {
            MainPageViewModel vm = this.DataContext as MainPageViewModel;
            bool isCtrlPressed = IsModiferKeyPressed(VirtualKey.Control);
            bool isShiftPressed = IsModiferKeyPressed(VirtualKey.Shift);
            if (isCtrlPressed)
            {
                switch (e.VirtualKey)
                {
                    case VirtualKey.N:
                        vm.AddDocumentCommand.Execute(null);
                        break;
                    case VirtualKey.Tab:
                        if (isShiftPressed)
                            vm.DocumentList.Prev();
                        else
                            vm.DocumentList.Next();
                        break;
                    case VirtualKey.F:
                    case VirtualKey.H:
                        this.FindButton.Flyout.ShowAt(this.FindButton);
                        break;
                    case VirtualKey.G:
                        this.GoToButton.Flyout.ShowAt(this.GoToButton);
                        break;
                    case VirtualKey.S:
                        vm.SaveCommand.Execute(null);
                        break;
                    case VirtualKey.O:
                        vm.OpenFileCommand.Execute(null);
                        break;
                }
            }
        }

        private void Flyout_Closed(object sender, object e)
        {
            //ユーザーがフライアウトを閉じたら見せる必要はない
            MainPageViewModel vm = this.DataContext as MainPageViewModel;
            if (vm != null)
                vm.Result = null;
        }

        private void Grid_DragOver(object sender, DragEventArgs e)
        {
            e.AcceptedOperation = Windows.ApplicationModel.DataTransfer.DataPackageOperation.Copy;
            e.Handled = true;
        }

        private async void Grid_Drop(object sender, DragEventArgs e)
        {
            var d = e.GetDeferral();

            if (e.DataView.Contains(Windows.ApplicationModel.DataTransfer.StandardDataFormats.StorageItems))
            {
                MainPageViewModel vm = this.DataContext as MainPageViewModel;
                // ファイルのパス一覧を取得する
                var items = await e.DataView.GetStorageItemsAsync();
                foreach(StorageFile item in items)
                {
                    await vm.DocumentList.AddFromFile(item);
                }
            }

            d.Complete();
        }
    }
}