#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.IO
Imports System.Linq
Imports System.Windows.Forms
Imports CSMediaProperties

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

    ''' <summary>
    ''' Create new instance of the CSVideoConverter library.
    ''' </summary>
    Private _CSVideoConverter As CSVideoConverter.VideoConverter

    ''' <summary>
    ''' CSharpImpl helper class
    ''' </summary>
    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

    ''' <summary>
    ''' frmMain_Load
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub frmMain_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    End Sub

    ''' <summary>
    ''' Get all the information about the source media file in a new window
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub cmdMediaProperties_Click(sender As Object, e As EventArgs) Handles cmdMediaProperties.Click
        Dim fMediaInformation As frmMediaProperties = New frmMediaProperties()
        fMediaInformation.LoadMediaFile(Me.txtSource.Text)
        fMediaInformation.ShowDialog()
    End Sub


    ''' <summary>
    ''' The real time preview works on video files only. Check if the destination is audio.
    ''' </summary>
    ''' <returns></returns>
    Public Function IsAudio() As Boolean
        Dim format As String = Me.cboDestinationFormat.Text
        Return Equals(format, "MP3") OrElse Equals(format, "OGG") OrElse Equals(format, "WAV") OrElse Equals(format, "WMA")
    End Function

    ''' <summary>
    ''' Convert
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub cmdConvert_Click(sender As Object, e As EventArgs) Handles cmdConvert.Click
        Try
            'Create a new instance of the library with the direction of the ffmpeg libraries

            Dim LibsPath As String = ""

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

            _CSVideoConverter = New CSVideoConverter.VideoConverter("UserName", "RegKey", LibsPath)

            'Set the source file
            _CSVideoConverter.FileSource = Me.txtSource.Text

            'Set the destination file
            _CSVideoConverter.FileDestination = Me.txtDestination.Text

            'Optional. Set the image / picture box control for real time preview.
            'Use the preview for video files only.
            If Not IsAudio() Then _CSVideoConverter.SetPicView(Me.videoPreviewWF1.Preview)

            'Set the video and the audio properties of the destination media file.
#Region "VideoAudioProperties"

            'Leave one or more properties empty will make the ffmpeg to use the default setting of the property.

            'Set the video codec:
            _CSVideoConverter.VideoCodec = Me.txtVideoCodec.Text

            'Set the bitrate (add K for kilobytes)
            _CSVideoConverter.VideoBitrate = Me.txtVideoBitrate.Text

            'Set the frames per seconds
            _CSVideoConverter.VideoFPS = Me.txtFPS.Text

            'Set the resolution
            _CSVideoConverter.VideoResolutionX = Me.txtVideoResolutionX.Text
            _CSVideoConverter.VideoResolutionY = Me.txtVideoResolutionY.Text

            'Set the Audio properties
            _CSVideoConverter.AudioBitrate = Me.txtAudioBitrate.Text
            _CSVideoConverter.AudioSamplerate = Me.txtAudioSampeRate.Text
            _CSVideoConverter.AudioChannels = Me.txtAudioChannels.Text

#End Region

            'Set the length to convert. 
#Region "Length"

            'From TimeSpan value. If 0 the library will convert the media file from the start.
            Dim from_time As TimeSpan = New TimeSpan(Me.timeFrom.Value.Hour, Me.timeFrom.Value.Minute, Me.timeFrom.Value.Second)

            'Length to convert of TimeSpan value. If 0 the library will convert the media until the end.
            Dim length_time As TimeSpan = New TimeSpan(Me.timeLength.Value.Hour, Me.timeLength.Value.Minute, Me.timeLength.Value.Second)

            'Set values
            _CSVideoConverter.FromTime = from_time
            _CSVideoConverter.LengthTime = length_time

#End Region

            'Set the ID3 tags
#Region "ID3Tags"

            'Create an instance of ID3Tags
            Dim iD3Tags As ID3Tags = New ID3Tags()

            'Set the ID3 tags values
            iD3Tags.Title = Me.txtID3Title.Text
            iD3Tags.Comment = Me.txtID3Comment.Text
            iD3Tags.Album = Me.txtID3Album.Text
            iD3Tags.Artist = Me.txtID3Artist.Text
            iD3Tags.Date = Me.txtID3Date.Text

            'Set the ID3 tags
            _CSVideoConverter.SetID3Tags(iD3Tags)

#End Region

            'Additional
#Region "Additional"

            'You can add an additional arguments:
            '_CSVideoConverter.ArgsAdditional = "-vtag xvid -more arg1";

            'Or if you want to set your own arguments:
            '_CSVideoConverter.ArgsDirect = "Your_own_arguments";

            'You can get the final arguments after setting the library properties:
            'string cmd = _CSVideoConverter.GetArgs();
            'Debug.WriteLine(cmd);

#End Region

            'Events
#Region "Events"

            'On start event
            AddHandler _CSVideoConverter.OperationStart, Sub(o)
                                                             Me.lblStatus.Text = "Start"
                                                             Debug.WriteLine("Start")
                                                         End Sub


            'On output
            AddHandler _CSVideoConverter.OperationOutput, Sub(o, s) Debug.WriteLine(s)

            'On progress event
            AddHandler _CSVideoConverter.OperationProgress, Sub(o, Precents, ConvertingProperties)

                                                                Try
                                                                    'Display the converting operation parameters 
                                                                    Me.lblStatus.Text = "Frame:" & ConvertingProperties.Frame & " Size:" & ConvertingProperties.Size & " FPS:" & ConvertingProperties.Fps & " Time:" & ConvertingProperties.Time.ToString() & " Bitrate:" & ConvertingProperties.Bitrate & " Speed:" & ConvertingProperties.Speed

                                                                    'Display the percents of the converting operation
                                                                    Me.progressBar1.Value = Precents
                                                                Catch
                                                                End Try

                                                            End Sub


            'Done
            AddHandler _CSVideoConverter.OperationDone, Sub(o, Aborted)
                                                            'Aborted = true if the user was aborted the operation
                                                            If Aborted Then
                                                                Me.lblStatus.Text = "Done (Aborted)."
                                                                Debug.WriteLine("Done (Aborted).")
                                                            Else
                                                                Me.lblStatus.Text = "Done."
                                                                Debug.WriteLine("Done")
                                                            End If
                                                        End Sub


            'Closed 
            AddHandler _CSVideoConverter.OperationClosed, Sub(o)
                                                              Me.lblStatus.Text = "Closed"
                                                              Debug.WriteLine("Closed")
                                                          End Sub


#End Region

            'Start the converting operation
            _CSVideoConverter.Run()
        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
        End Try
    End Sub

    ''' <summary>
    ''' Stop.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub cmdStop_Click(sender As Object, e As EventArgs) Handles cmdStop.Click
        Try
            _CSVideoConverter.Abort()
        Catch
        End Try
    End Sub

    ''' <summary>
    ''' Pause.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub cmdPause_Click(sender As Object, e As EventArgs) Handles cmdPause.Click
        Try
            _CSVideoConverter.Pause()
        Catch
        End Try
    End Sub

    ''' <summary>
    ''' Resume.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub cmdResume_Click(sender As Object, e As EventArgs) Handles cmdResume.Click
        Try
            _CSVideoConverter.Resume()
        Catch
        End Try
    End Sub

    ''' <summary>
    ''' Open media file and get the information.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    <Obsolete>
    Private Async Sub cmdOpenMedia_Click(sender As Object, e As EventArgs) Handles cmdOpenMedia.Click
        Try
            Dim openFileDialog1 As OpenFileDialog = New OpenFileDialog()

            If openFileDialog1.ShowDialog() <> DialogResult.OK Then
                Return
            End If

            Me.txtSource.Text = openFileDialog1.FileName

            'Create a new instance of the library with the direction of the ffmpeg libraries

            Dim LibsPath As String = ""


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

            Using CSharpImpl.__Assign(_CSVideoConverter, New CSVideoConverter.VideoConverter("UserName", "RegKey", LibsPath))
                'Set the destination file:
                Me.txtDestination.Text = Path.GetDirectoryName(Me.txtSource.Text) & "\" & Path.GetFileName(Me.txtSource.Text) & "." & Me.cboDestinationFormat.Text
                Dim mediaProperties As MediaProperties
                mediaProperties = Await _CSVideoConverter.Open(Me.txtSource.Text)

#Region "GetID3Tags"

                If mediaProperties.Format Is Nothing Then Return

                'Load the ID3 tags
                Me.txtID3Title.Text = ""
                Me.txtID3Comment.Text = ""
                Me.txtID3Artist.Text = ""
                Me.txtID3Album.Text = ""
                Me.txtID3Date.Text = ""
                If mediaProperties.Format.Tags.FirstOrDefault(Function(tag) Equals(tag.Key, "title")) IsNot Nothing Then Me.txtID3Title.Text = Enumerable.FirstOrDefault(mediaProperties.Format.Tags, Function(tag) Equals(tag.Key, "title")).Value
                If mediaProperties.Format.Tags.FirstOrDefault(Function(tag) Equals(tag.Key, "comment")) IsNot Nothing Then Me.txtID3Comment.Text = Enumerable.FirstOrDefault(mediaProperties.Format.Tags, Function(tag) Equals(tag.Key, "comment")).Value
                If mediaProperties.Format.Tags.FirstOrDefault(Function(tag) Equals(tag.Key, "artist")) IsNot Nothing Then Me.txtID3Artist.Text = Enumerable.FirstOrDefault(mediaProperties.Format.Tags, Function(tag) Equals(tag.Key, "artist")).Value
                If mediaProperties.Format.Tags.FirstOrDefault(Function(tag) Equals(tag.Key, "album")) IsNot Nothing Then Me.txtID3Album.Text = Enumerable.FirstOrDefault(mediaProperties.Format.Tags, Function(tag) Equals(tag.Key, "album")).Value
                If mediaProperties.Format.Tags.FirstOrDefault(Function(tag) Equals(tag.Key, "date")) IsNot Nothing Then Me.txtID3Date.Text = Enumerable.FirstOrDefault(mediaProperties.Format.Tags, Function(tag) Equals(tag.Key, "date")).Value

#End Region
            End Using

        Catch ex As Exception
            MessageBox.Show(ex.Message)
        Finally
        End Try
    End Sub

    ''' <summary>
    ''' Set the destination format of the destination file.
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub cboDestinationFormat_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cboDestinationFormat.SelectedIndexChanged

        On Error Resume Next

        Debug.WriteLine(Me.cboDestinationFormat.Text)

        'Set MP4 as default if the user select --Video--
        If Equals(Me.cboDestinationFormat.Text, "--Video--") Then Me.cboDestinationFormat.Text = "MP4"

        'Set MP3 as default if the user select --Video--
        If Equals(Me.cboDestinationFormat.Text, "--Audio--") Then Me.cboDestinationFormat.Text = "Mp3"

        'Set the destination file:
        Me.txtDestination.Text = Path.GetDirectoryName(Me.txtSource.Text) & "\" & Path.GetFileName(Me.txtSource.Text) & "." & Me.cboDestinationFormat.Text
    End Sub

    ''' <summary>
    ''' Safe exit. 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    Private Sub frmMain_FormClosing(sender As Object, e As FormClosingEventArgs) Handles MyBase.FormClosing
        'Abort the conversion
        Try
            _CSVideoConverter.Abort()
        Catch
        End Try
    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-video-converter/?cmd=order

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

End Class
