#Region "LICENSE"
'
' Copyright (c) Microncode.com
' 
' This source is subject to the Microsoft Public License. 
' See https://opensource.org/licenses/ms-pl.html.
' All other rights reserved. 
' 
' THIS CODE AND INFORMATION IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, 
' EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED 
' WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. 
'
#End Region

Imports System
Imports System.Diagnostics
Imports System.Drawing
Imports System.Windows.Forms
Imports CSPhantomJS

''' <summary>
''' The main winform example of using the CSPhantomJS.
''' </summary>
Public Class frmMain
    Inherits Form

    ''' <summary>
    ''' Declare the library.
    ''' </summary>
    Private _WebpageCapture As CSPhantomJS.CSPhantomJS
    Private _FileName As String = ""

    ''' <summary>
    ''' Enable / disable the capture buttons
    ''' </summary>
    ''' <paramname="state"></param>
    Private Sub EnaDisButtons(ByVal state As Boolean)
        Me.cmdCapture.Enabled = state
        Me.cmdCaptureAsync.Enabled = state
        Me.cmdOpenImage.Enabled = state
    End Sub

    ''' <summary>
    ''' Capture a web page with events.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub cmdCapture_Click(sender As Object, e As EventArgs) Handles cmdCapture.Click
        'Set the destination image file name
        _FileName = Application.StartupPath & "\" & Date.Now.ToString("yyyy-MM-dd-HH-mm-ss") & "." & Me.cboImageFormat.Text

        'Create a new instance of the library with the 
        'direction of the phantomjs libraries. 

        _WebpageCapture = New CSPhantomJS.CSPhantomJS("UserName", "RegKey")
        _WebpageCapture.DestinationFormat = DestinationFormat.Image
        _WebpageCapture.ImageFormat = "1920px"
        _WebpageCapture.URL = Me.txtURL.Text
        _WebpageCapture.OutFile = _FileName

#Region "Events"

        'Set the progress bar max to 3 (stages)
        Me.progressBar1.Maximum = 3

        'On start event
        AddHandler _WebpageCapture.OperationStart, Sub(o)
                                                       Debug.WriteLine("Start")
                                                       Me.lblState.Text = "Start"

                                                       'Disable the relevant buttons
                                                       EnaDisButtons(False)

                                                       'Set the progress bar
                                                       Me.progressBar1.Value = 1
                                                   End Sub


        'On progress event
        AddHandler _WebpageCapture.OperationOutput, Sub(o, s)
                                                        Debug.WriteLine(s)
                                                        Me.lblState.Text = "Capturing..."

                                                        'Display the results in the text box
                                                        Me.txtResults.Text = Me.txtResults.Text & Microsoft.VisualBasic.Constants.vbCrLf & s
                                                        Me.txtResults.Select(Me.txtResults.TextLength + 1, 0)
                                                        Me.txtResults.SelectedText = s

                                                        'Set the progress bar
                                                        Me.progressBar1.Value = 2
                                                    End Sub


        'On closed
        AddHandler _WebpageCapture.OperationClosed, Sub(o)
                                                        Debug.WriteLine("Closed")
                                                        Me.lblState.Text = "Ready."
                                                        Me.picPreview.Image = Image.FromFile(_FileName)
                                                        Me.picPreview.SizeMode = PictureBoxSizeMode.StretchImage
                                                        Me.picPreview.Refresh()
                                                        EnaDisButtons(True)
                                                    End Sub


        'On done
        AddHandler _WebpageCapture.OperationDone, Sub(o)
                                                      Me.Invoke(New Action(Sub()
                                                                               Debug.WriteLine("Done")
                                                                               Me.lblState.Text = "Ready."

                                                                               'Set the progress bar
                                                                               Me.progressBar1.Value = 3

                                                                               'Enable the relevant buttons
                                                                               EnaDisButtons(False)
                                                                           End Sub))
                                                  End Sub


#End Region

        'Start the capture operation
        _WebpageCapture.Capture()
    End Sub

    ''' <summary>
    ''' Cancel the capturing process.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub cmdCancel_Click(sender As Object, e As EventArgs) Handles cmdCancel.Click
        _WebpageCapture.Abort()
    End Sub

    ''' <summary>
    ''' Capture in Async mode.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Async Sub cmdCaptureAsync_Click(sender As Object, e As EventArgs) Handles cmdCaptureAsync.Click
        Dim LibsPath As String = ""


        'If the LibsPath is empty or "" the library will search for
        'the PhantomJS libraries under the path:
        '[AssemblyDirectory]\CSPlugins\PhantomJS\[x86|x64]\

        Using _WebpageCapture = New CSPhantomJS.CSPhantomJS("UserName", "RegKey", LibsPath)
            _FileName = Application.StartupPath & "\" & Date.Now.ToString("yyyy-MM-dd-HH-mm-ss") & ".png"
            _WebpageCapture.DestinationFormat = DestinationFormat.Image
            _WebpageCapture.ImageFormat = "1920px"
            _WebpageCapture.URL = Me.txtURL.Text
            _WebpageCapture.OutFile = _FileName

            'Disable the buttons
            EnaDisButtons(False)
            Me.lblState.Text = "Capturing..."

            'Capture async
            Await _WebpageCapture.CaptureAsync()
            Debug.WriteLine("Done.")
            Me.lblState.Text = "Ready."

            'Enable the button
            EnaDisButtons(True)

            'Display the image
            Me.picPreview.Image = Image.FromFile(_FileName)
            Me.picPreview.SizeMode = PictureBoxSizeMode.StretchImage
            Me.picPreview.Refresh()
        End Using
    End Sub

    ''' <summary>
    ''' Open the path of the image.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub cmdOpenPath_Click(sender As Object, e As EventArgs) Handles cmdOpenPath.Click
        Dim argument As String = "/select, """ & Application.StartupPath & """"
        Process.Start("explorer.exe", argument)
    End Sub

    ''' <summary>
    ''' Display the image in the default image viewer of windows.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub cmdOpenImage_Click(sender As Object, e As EventArgs) Handles cmdOpenImage.Click
        'If the OpenImage button is disable (on capturing)
        'the image file is not existed.
        If Not Me.cmdOpenImage.Enabled Then Return

        'Display the image in the default image viewer of windows.
        Dim photoViewer As Process = New Process()
        photoViewer.StartInfo.FileName = _FileName
        photoViewer.Start()
    End Sub

    ''' <summary>
    ''' Display the image when click on the picPreview image control.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub picPreview_Click(sender As Object, e As EventArgs) Handles picPreview.Click
        cmdOpenImage_Click(sender, e)
    End Sub

    ''' <summary>
    ''' Order a license.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub cmdOrderLicense_Click(sender As Object, e As EventArgs) Handles cmdOrderLicense.Click
        'In order to get your own UserName and RegKey and to distribute this library
        'with your own projects for commercial or any other purpose, please order a license at:
        'https://www.microncode.com/developers/cs-phantomjs/?cmd=order

        Process.Start("https://www.microncode.com/developers/cs-phantomjs/?cmd=order")
    End Sub


    Private Class CSharpImpl
        <Obsolete("Please refactor calling code to use normal Visual Basic assignment")>
        Shared Function __Assign(Of T)(ByRef target As T, value As T) As T
            target = value
            Return value
        End Function
    End Class

End Class
