#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 CSPhantomJSExampleWinform
{
    using System;
    using System.Diagnostics;
    using System.Drawing;
    using System.Windows.Forms;
    using CSPhantomJS;

    /// <summary>
    /// The main winform example of using the CSPhantomJS.
    /// </summary>
    public partial class frmMain : Form
    {
        /// <summary>
        /// Declare the library.
        /// </summary>
        CSPhantomJS _WebpageCapture;
        string _FileName = "";

        /// <summary>
        /// Constructor
        /// </summary>
        public frmMain()
        {
            InitializeComponent();
        }

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

        }

        /// <summary>
        /// Enable / disable the capture buttons
        /// </summary>
        /// <param name="state"></param>
        private void EnaDisButtons(bool state)
        {
            cmdCapture.Enabled = state;
            cmdCaptureAsync.Enabled = state;
            cmdOpenImage.Enabled = state;
        }

        /// <summary>
        /// Capture a web page with events.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdCapture_Click(object sender, EventArgs e)
        {
            //Set the destination image file name
            _FileName = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + "." + cboImageFormat.Text;

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

            _WebpageCapture = new CSPhantomJS("UserName", "RegKey");

            _WebpageCapture.DestinationFormat = DestinationFormat.Image;
            _WebpageCapture.ImageFormat = "1920px";
            _WebpageCapture.URL = txtURL.Text;
            _WebpageCapture.OutFile = _FileName;

            #region Events

            //Set the progress bar max to 3 (stages)
            progressBar1.Maximum = 3;

            //On start event
            _WebpageCapture.OperationStart += (o) =>
            {
                Debug.WriteLine("Start");
                lblState.Text = "Start";

                //Disable the relevant buttons
                EnaDisButtons(false);

                //Set the progress bar
                progressBar1.Value = 1;
            };

            //On progress event
            _WebpageCapture.OperationOutput += (o, s) =>
            {
                Debug.WriteLine(s);
                lblState.Text = "Capturing...";

                //Display the results in the text box
                txtResults.Text = txtResults.Text + "\r\n" + s;
                txtResults.Select(txtResults.TextLength + 1, 0);
                txtResults.SelectedText = s;

                //Set the progress bar
                progressBar1.Value = 2;
            };

            //On closed
            _WebpageCapture.OperationClosed += (o) =>
            {
                Debug.WriteLine("Closed");
                lblState.Text = "Ready.";

                picPreview.Image = Image.FromFile(_FileName);
                picPreview.SizeMode = PictureBoxSizeMode.StretchImage;
                picPreview.Refresh();

                EnaDisButtons(true);
            };

            //On done
            _WebpageCapture.OperationDone += (o) =>
            {
                this.Invoke(new Action(() =>
                {
                    Debug.WriteLine("Done");
                    lblState.Text = "Ready.";

                    //Set the progress bar
                    progressBar1.Value = 3;

                    //Enable the relevant buttons
                    EnaDisButtons(false);

                }));
            };

            #endregion

            //Start the capture operation
            _WebpageCapture.Capture();

        }

        /// <summary>
        /// Cancel the capturing process.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdCancel_Click(object sender, EventArgs e)
        {
            _WebpageCapture.Abort();
        }

        /// <summary>
        /// Capture in Async mode.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void cmdCaptureAsync_Click(object sender, EventArgs e)
        {
            string LibsPath = "";

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

            using (var _WebpageCapture = new CSPhantomJS("UserName", "RegKey", LibsPath))
            {
                _FileName = Application.StartupPath + "\\" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".png";

                _WebpageCapture.DestinationFormat = DestinationFormat.Image;
                _WebpageCapture.ImageFormat = "1920px";
                _WebpageCapture.URL = txtURL.Text;
                _WebpageCapture.OutFile = _FileName;

                //Disable the buttons
                EnaDisButtons(false);

                lblState.Text = "Capturing...";

                //Capture async
                await _WebpageCapture.CaptureAsync();

                Debug.WriteLine("Done.");

                lblState.Text = "Ready.";

                //Enable the button
                EnaDisButtons(true);

                //Display the image
                picPreview.Image = Image.FromFile(_FileName);
                picPreview.SizeMode = PictureBoxSizeMode.StretchImage;
                picPreview.Refresh();
            }
        }

        /// <summary>
        /// Open the path of the image.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdOpenPath_Click(object sender, EventArgs e)
        {
            string argument = "/select, \"" + Application.StartupPath + "\"";

            Process.Start("explorer.exe", argument);
        }

        /// <summary>
        /// Display the image in the default image viewer of windows.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void cmdOpenImage_Click(object sender, EventArgs e)
        {
            //If the OpenImage button is disable (on capturing)
            //the image file is not existed.
            if (!cmdOpenImage.Enabled) return;

            //Display the image in the default image viewer of windows.
            Process photoViewer = new Process();
            photoViewer.StartInfo.FileName = _FileName;
            photoViewer.Start();

        }

        /// <summary>
        /// Display the image when click on the picPreview image control.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void picPreview_Click(object sender, EventArgs e)
        {
            cmdOpenImage_Click(sender, e);
        }

        /// <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-phantomjs/?cmd=order
            /// 
            System.Diagnostics.Process.Start("https://www.microncode.com/developers/cs-phantomjs/?cmd=order");
        }

    }
}
