/*
 * Copyright (C) 2013 FooProject
 * * This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 3 of the License, or (at your option) any later version.

 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of 
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Windows.Graphics.Printing;
using Windows.Storage.Pickers;
using Windows.Storage;
using Windows.UI.ViewManagement;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.UI.ApplicationSettings;
using FooEditEngine;
using FooEditEngine.Metro;

// 空白ページのアイテム テンプレートについては、http://go.microsoft.com/fwlink/?LinkId=234238 を参照してください

namespace Test
{
    /// <summary>
    /// それ自体で使用できる空白ページまたはフレーム内に移動できる空白ページ。
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
            this.Current_ChangedSetting(AppSettings.Current, null);
            InputPane currentView = InputPane.GetForCurrentView();
            currentView.Showing += currentView_Showing;
            currentView.Hiding += currentView_Hiding;
            PrintManager.GetForCurrentView().PrintTaskRequested += MainPage_PrintTaskRequested;
        }

        void MainPage_PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
        {
            FooPrintText printtext = new FooPrintText();
            printtext.Fotter = "fotter";
            printtext.Header = "header";
            printtext.Padding = new FooEditEngine.Padding(20, 20, 20, 20);
            printtext.Print(args.Request, "Text Print", this.fooTextBox);
        }

        /// <summary>
        /// このページがフレームに表示されるときに呼び出されます。
        /// </summary>
        /// <param name="e">このページにどのように到達したかを説明するイベント データ。Parameter 
        /// プロパティは、通常、ページを構成するために使用します。</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            AppSettings.Current.ChangedSetting += Current_ChangedSetting;
        }

        void currentView_Hiding(InputPane sender, InputPaneVisibilityEventArgs args)
        {
            this.fooTextBox.Margin = new Thickness(0);
            args.EnsuredFocusedElementInView = true;
        }

        void currentView_Showing(InputPane sender, InputPaneVisibilityEventArgs args)
        {
            this.fooTextBox.Margin = new Thickness(0, 0, 0, args.OccludedRect.Height);
            args.EnsuredFocusedElementInView = true;
        }

        void Current_ChangedSetting(object sender, EventArgs e)
        {
            AppSettings setting = (AppSettings)sender;
            this.fooTextBox.FlowDirection = setting.IsRTL ? FlowDirection.RightToLeft : FlowDirection.LeftToRight;
            this.fooTextBox.DrawCaretLine = setting.ShowLineMarker;
            this.fooTextBox.DrawLineNumber = setting.ShowLineNumber;
            this.fooTextBox.DrawRuler = setting.ShowRuler;
            if (setting.HilightXML)
            {
                this.fooTextBox.Hilighter = new XmlHilighter();
                this.fooTextBox.LayoutLineCollection.HilightAll();
            }
            else
            {
                this.fooTextBox.Hilighter = null;
                this.fooTextBox.LayoutLineCollection.ClearHilight();
            }
            this.fooTextBox.LineBreakMethod = setting.CurrentLineBreakMethod.Method;
            this.fooTextBox.LineBreakCharCount = 50;
            this.fooTextBox.Refresh();
        }

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            FileOpenPicker openPicker = new FileOpenPicker();

            openPicker.ViewMode = PickerViewMode.List;

            // ファイル形式
            openPicker.FileTypeFilter.Add("*");

            // 最初に表示される場所
            openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;

            StorageFile file = await openPicker.PickSingleFileAsync();
            if (file != null)
            {
                this.fooTextBox.IsEnabled = false;
                using (Stream stream = await file.OpenStreamForReadAsync())
                using(StreamReader reader = new StreamReader(stream))
                {
                    await this.fooTextBox.LoadFileAsync(reader,null);
                    this.fooTextBox.FoldingStrategy = new CharFoldingMethod('{', '}');
                    this.fooTextBox.LayoutLineCollection.GenerateFolding();
                    this.fooTextBox.IsEnabled = true;
                    this.fooTextBox.Refresh();
                }
            }
        }

        private async void Button_Click_1(object sender, RoutedEventArgs e)
        {
            FileSavePicker savePicker = new FileSavePicker();
            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            savePicker.FileTypeChoices.Add("Text Types", new List<string>() { ".txt" });
            savePicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
            StorageFile file = await savePicker.PickSaveFileAsync();
            if (file != null)
            {
                using (Stream stream = await file.OpenStreamForWriteAsync())
                using (StreamWriter writer = new StreamWriter(stream))
                {
                    await this.fooTextBox.SaveFile(writer,null);
                }
            }
        }

    }
}
