Imports C1.Xaml.Document
Imports C1.Xaml.FlexViewer

Imports Windows.Storage
Imports Windows.Storage.Pickers
Imports Windows.UI.Popups

Partial Public NotInheritable Class MainPage
    Inherits Page

    Const c_CheckedGlyph As String = ChrW(&HE0A2)
    Const c_UncheckedGlyph As String = ChrW(&HE003)

    Private _pdfDocSource As C1PdfDocumentSource
    Private _closeToolItem As ToolMenuItem
    Private _useSystemRenderingToolItem As ToolMenuItem
    Private _appView As ApplicationView
    Private _useSystemRendering As Boolean = True

    Public Sub New()
        Me.InitializeComponent()

        AddHandler Me.Unloaded, AddressOf MainPage_Unloaded
        AddHandler Me.Loaded, AddressOf MainPage_Loaded

        AddHandler flexViewer.PrepareToolMenu, AddressOf FlexViewer_PrepareToolMenu
        AddHandler flexViewer.NavigateToCustomTool, AddressOf FlexViewer_NavigateToCustomTool
        _appView = ApplicationView.GetForCurrentView()
    End Sub

    Friend Sub App_Suspending()
        flexViewer.Pane.HandleSuspending()
    End Sub

    Private Sub FlexViewer_PrepareToolMenu(sender As Object, e As EventArgs)
        Dim items = DirectCast(sender, C1FlexViewer).ToolMenuItems
        For i As Integer = items.Count - 1 To 0 Step -1
            Select Case items(i).Tool
                Case FlexViewerTool.Outlines, FlexViewerTool.PageSettings, FlexViewerTool.Parameters
                    items.RemoveAt(i)
                    Exit Select
            End Select
        Next
        items.Insert(0, New ToolMenuItem(ChrW(&HE155), FlexViewerTool.CustomTool1, Strings.OpenToolLabel))
        _useSystemRenderingToolItem = New ToolMenuItem(c_CheckedGlyph, FlexViewerTool.CustomTool3, Strings.UseSystemRenderingToolLabel)
        items.Add(_useSystemRenderingToolItem)
        _closeToolItem = New ToolMenuItem(ChrW(&HE10A), FlexViewerTool.CustomTool2, Strings.CloseToolLabel)
        items.Add(_closeToolItem)
    End Sub

    Private Async Sub FlexViewer_NavigateToCustomTool(sender As Object, e As CustomToolEventArgs)
        If e.Tool = FlexViewerTool.CustomTool1 Then
            Await OpenPdf()
        ElseIf e.Tool = FlexViewerTool.CustomTool2 Then
            ClosePdf()
        ElseIf e.Tool = FlexViewerTool.CustomTool3 Then
            Await ChangeUseSystemRendering()
        End If
    End Sub

    Private Sub MainPage_Unloaded(sender As Object, e As RoutedEventArgs)
        ClosePdf()
    End Sub

    Private Async Sub MainPage_Loaded(sender As Object, e As RoutedEventArgs)
        Dim f = Await StorageFile.GetFileFromApplicationUriAsync(New Uri("ms-appx:///Assets/C1XapOptimizer.pdf"))
        Await LoadPdf(f)
    End Sub

    Private Sub CheckBox_Changed(sender As Object, e As RoutedEventArgs)
        If revealModeCheckBox.IsChecked = True Then
            passwordBox.PasswordRevealMode = PasswordRevealMode.Visible
        Else
            passwordBox.PasswordRevealMode = PasswordRevealMode.Hidden
        End If
    End Sub

    Private Async Function ChangeUseSystemRendering() As Task
        _closeToolItem.IsEnabled = False
        _useSystemRenderingToolItem.IsEnabled = False
        Try
            _useSystemRendering = Not _useSystemRendering
            If (_useSystemRendering) Then
                _useSystemRenderingToolItem.Glyph = c_CheckedGlyph
            Else
                _useSystemRenderingToolItem.Glyph = c_UncheckedGlyph
            End If
            If Not (_pdfDocSource Is Nothing) Then
                'System.Diagnostics.Debug.WriteLine("BEFORE ChangeUseSystemRendering")
                _pdfDocSource.UseSystemRendering = _useSystemRendering
                Await _pdfDocSource.GenerateAsync()
                'System.Diagnostics.Debug.WriteLine("AFTER  ChangeUseSystemRendering")
            End If
        Finally
            _closeToolItem.IsEnabled = True
            _useSystemRenderingToolItem.IsEnabled = True
        End Try
    End Function

    Private Async Function LoadPdf(file As StorageFile) As Task
        If _pdfDocSource Is Nothing Then
            _pdfDocSource = New C1PdfDocumentSource()
        End If
        flexViewer.DocumentSource = Nothing
        Dim commonEx As Exception = Nothing
        Try
            Dim passed As Boolean = False
            Try
                Await _pdfDocSource.LoadFromFileAsync(file)
                passed = True
            Catch ppe As PdfPasswordException
            End Try
            If Not passed Then
                fileNameBlock.Text = file.Name
                passwordBox.Password = String.Empty
                While Not passed
                    Dim res = Await passwordDialog.ShowAsync()
                    If res = ContentDialogResult.Primary Then
                        Try
                            Await _pdfDocSource.LoadFromFileAsync(file, passwordBox.Password)
                            passed = True
                        Catch ppe As PdfPasswordException
                        End Try
                    Else
                        ClosePdf()
                        Return
                    End If
                End While
            End If
            _appView.Title = file.DisplayName
            _closeToolItem.IsEnabled = True
        Catch ex As Exception
            commonEx = ex
            ClosePdf()
        End Try
        If commonEx IsNot Nothing Then
            Dim md As New MessageDialog(String.Format(Strings.PdfErrorFormat, file.Name, commonEx.Message), Strings.ErrorTitle)
            Await md.ShowAsync()
            Return
        End If
        flexViewer.DocumentSource = _pdfDocSource
    End Function

    Private Sub ClosePdf()
        If _pdfDocSource IsNot Nothing Then
            flexViewer.DocumentSource = Nothing
            _pdfDocSource.Dispose()
            _pdfDocSource = Nothing

            _closeToolItem.IsEnabled = False
            _appView.Title = String.Empty
        End If
    End Sub

    Private Async Function OpenPdf() As Task
        Dim fop As New FileOpenPicker()
        fop.SuggestedStartLocation = PickerLocationId.DocumentsLibrary
        fop.ViewMode = PickerViewMode.List
        fop.FileTypeFilter.Clear()
        fop.FileTypeFilter.Add(".pdf")
        Dim file As StorageFile = Await fop.PickSingleFileAsync()
        If file IsNot Nothing Then
            Await LoadPdf(file)
        End If
    End Function
End Class
