#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. 
//
#endregion

namespace CSVideoConverterExample
{
    using System;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Windows.Forms;
    using CSMediaProperties;

    /// <summary>
    /// The main example of using the CSVideoConverter library.
    /// </summary>
    public partial class frmMain : Form
    {
        /// <summary>
        /// Create new instance of the CSVideoConverter library.
        /// </summary>
        CSVideoConverter.VideoConverter _CSVideoConverter;

        public frmMain()
        {
            InitializeComponent();
        }

        /// <summary>
        /// Get all the information about the source media file in a new window
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdMediaProperties_Click(object sender, EventArgs e)
        {
            frmMediaProperties fMediaInformation = new frmMediaProperties();

            fMediaInformation.LoadMediaFile(txtSource.Text);

            fMediaInformation.ShowDialog();
        }

        /// <summary>
        /// The real time preview works on video files only. Check if the destination is audio.
        /// </summary>
        /// <returns></returns>
        public bool IsAudio()
        {
            string format = cboDestinationFormat.Text;

            return ((format == "MP3") || (format == "OGG") || (format == "WAV") || (format == "WMA"));
        }

        /// <summary>
        /// Convert
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdConvert_Click(object sender, EventArgs e)
        {
           try
            {
                //Create a new instance of the library with the direction of the ffmpeg libraries

                string LibsPath = "";

                //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 = txtSource.Text;

                //Set the destination file
                _CSVideoConverter.FileDestination = txtDestination.Text;

                //Optional. Set the image / picture box control for real time preview.
                //Use the preview for video files only.
                if(!IsAudio())
                    _CSVideoConverter.SetPicView(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 = txtVideoCodec.Text;

                //Set the bitrate (add K for kilobytes)
                _CSVideoConverter.VideoBitrate = txtVideoBitrate.Text;

                //Set the frames per seconds
                _CSVideoConverter.VideoFPS = txtFPS.Text;

                //Set the resolution
                _CSVideoConverter.VideoResolutionX = txtVideoResolutionX.Text;
                _CSVideoConverter.VideoResolutionY = txtVideoResolutionY.Text;

                //Set the Audio properties
                _CSVideoConverter.AudioBitrate = txtAudioBitrate.Text;
                _CSVideoConverter.AudioSamplerate = txtAudioSampeRate.Text;
                _CSVideoConverter.AudioChannels = txtAudioChannels.Text;

                #endregion

                //Set the length to convert. 
                #region Length

                //From TimeSpan value. If 0 the library will convert the media file from the start.
                TimeSpan from_time = new TimeSpan(timeFrom.Value.Hour, timeFrom.Value.Minute, timeFrom.Value.Second);

                //Length to convert of TimeSpan value. If 0 the library will convert the media until the end.
                TimeSpan length_time = new TimeSpan(timeLength.Value.Hour, timeLength.Value.Minute, timeLength.Value.Second);

                //Set values
                _CSVideoConverter.FromTime = from_time;
                _CSVideoConverter.LengthTime = length_time;

                #endregion

                //Set the ID3 tags
                #region ID3Tags

                //Create an instance of ID3Tags
                ID3Tags iD3Tags = new ID3Tags();

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

                //Set the ID3 tags
                _CSVideoConverter.SetID3Tags(iD3Tags);

                #endregion

                //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);

                #endregion

                //Events
                #region Events

                //On start event
                _CSVideoConverter.OperationStart += (o) =>
                {
                    lblStatus.Text = "Start";
                    Debug.WriteLine("Start");
                };

                //On output
                _CSVideoConverter.OperationOutput += (o, s) =>
                {
                    Debug.WriteLine(s);
                };

                //On progress event
                _CSVideoConverter.OperationProgress += (o, Precents, ConvertingProperties) =>
                {
                        this.Invoke(new Action(() =>
                        {
                            try
                            {
                                //Display the converting operation parameters 
                                lblStatus.Text = "Frame:" + ConvertingProperties.Frame
                                                    + " Size:" + ConvertingProperties.Size
                                                    + " FPS:" + ConvertingProperties.Fps
                                                    + " Time:" + ConvertingProperties.Time
                                                    + " Bitrate:" + ConvertingProperties.Bitrate
                                                    + " Speed:" + ConvertingProperties.Speed;

                                //Display the percents of the converting operation
                                progressBar1.Value = Precents;
                            }

                            catch { }
                        }));

                };

                //Done
                _CSVideoConverter.OperationDone += (o, Aborted) =>
                {
                    //Aborted = true if the user was aborted the operation
                    if (Aborted)
                    {
                        lblStatus.Text = "Done (Aborted).";
                        Debug.WriteLine("Done (Aborted).");
                    }
                    else
                    {
                        lblStatus.Text = "Done.";
                        Debug.WriteLine("Done");
                    }

                };

                //Closed 
                _CSVideoConverter.OperationClosed += (o) =>
                {
                    lblStatus.Text = "Closed";
                    Debug.WriteLine("Closed");
                };

                #endregion

                //Start the converting operation
                _CSVideoConverter.Run();
                
            }
            
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {

            }
            
        }

        /// <summary>
        /// Stop
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdStop_Click(object sender, EventArgs e)
        {
            try { _CSVideoConverter.Abort(); }
            catch { }
        }

        /// <summary>
        /// Pause
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdPause_Click(object sender, EventArgs e)
        {
            try { _CSVideoConverter.Pause(); }
            catch { }
        }

        /// <summary>
        /// Resume
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdResume_Click(object sender, EventArgs e)
        {
            try { _CSVideoConverter.Resume(); }
            catch { }   
        }

        /// <summary>
        /// Form_Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmMain_Load(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// Open media file and get the information
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void cmdOpenMedia_Click(object sender, EventArgs e)
        {
            try 
            {
                OpenFileDialog openFileDialog1 = new OpenFileDialog();

                if (openFileDialog1.ShowDialog() != System.Windows.Forms.DialogResult.OK)
                {
                    return;
                }

                txtSource.Text = openFileDialog1.FileName;

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

                string LibsPath = "";

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

                using (_CSVideoConverter = new CSVideoConverter.VideoConverter("UserName", "RegKey", LibsPath))
                {
                    //Set the destination file:
                    txtDestination.Text = Path.GetDirectoryName(txtSource.Text) + @"\" + Path.GetFileName(txtSource.Text) + "." + cboDestinationFormat.Text;

                    CSMediaProperties.MediaProperties mediaProperties;
                    mediaProperties = await _CSVideoConverter.Open(txtSource.Text);

                    #region GetID3Tags

                    if (mediaProperties.Format == null)
                        return;

                    //Load the ID3 tags
                    txtID3Title.Text = "";
                    txtID3Comment.Text = "";
                    txtID3Artist.Text = "";
                    txtID3Album.Text = "";
                    txtID3Date.Text = "";

                    if (mediaProperties.Format.Tags.FirstOrDefault(tag => tag.Key == "title") != null)
                        txtID3Title.Text = mediaProperties.Format.Tags.FirstOrDefault(tag => tag.Key == "title").Value;

                    if (mediaProperties.Format.Tags.FirstOrDefault(tag => tag.Key == "comment") != null)
                        txtID3Comment.Text = mediaProperties.Format.Tags.FirstOrDefault(tag => tag.Key == "comment").Value;

                    if (mediaProperties.Format.Tags.FirstOrDefault(tag => tag.Key == "artist") != null)
                        txtID3Artist.Text = mediaProperties.Format.Tags.FirstOrDefault(tag => tag.Key == "artist").Value;

                    if (mediaProperties.Format.Tags.FirstOrDefault(tag => tag.Key == "album") != null)
                        txtID3Album.Text = mediaProperties.Format.Tags.FirstOrDefault(tag => tag.Key == "album").Value;

                    if (mediaProperties.Format.Tags.FirstOrDefault(tag => tag.Key == "date") != null)
                        txtID3Date.Text = mediaProperties.Format.Tags.FirstOrDefault(tag => tag.Key == "date").Value;

                    #endregion
                };

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {

            }

        }

        /// <summary>
        /// Set the destination format of the destination file.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cboDestinationFormat_SelectedIndexChanged(object sender, EventArgs e)
        {
            Debug.WriteLine(cboDestinationFormat.Text);

            //Set MP4 as default if the user select --Video--
            if (cboDestinationFormat.Text == "--Video--")
                cboDestinationFormat.Text = "MP4";

            //Set MP3 as default if the user select --Video--
            if (cboDestinationFormat.Text == "--Audio--")
                cboDestinationFormat.Text = "Mp3";

            //Set the destination file:
            txtDestination.Text = Path.GetDirectoryName(txtSource.Text) + @"\" + Path.GetFileName(txtSource.Text) + "." + cboDestinationFormat.Text;
        }

        /// <summary>
        /// Safe exit. 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            //Abort the conversion
            try { _CSVideoConverter.Abort(); }
            catch { }
        }

        /// <summary>
        /// Order a license.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdOrderLicense_Click(object sender, EventArgs e)
        {
            /// 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
            /// 
            System.Diagnostics.Process.Start("https://www.microncode.com/developers/cs-video-converter/?cmd=order");
        }
    }
}
