using System;
using System.Text;
using System.Threading;
using System.Windows.Forms;

/*
    Copyright (c) 2010 flixmonk. (http://DVDSwarm.codeplex.com)
    All Rights Reserved.
        
    Redistribution and use in source and binary forms, with or without modification,
    are permitted provided that the following conditions are met:
        
    * Redistributions of source code must retain the above copyright notice, this list
      of conditions and the following disclaimer.
        
    * Redistributions in binary form must reproduce the above copyright notice, this
    list of conditions and the following disclaimer in the documentation and/or other
    materials provided with the distribution. 
        
    * Neither the name of The Flixmonk nor the names of its contributors may be used to
    endorse or promote products derived from this software without specific prior written
    permission.
        
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY
    EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
    OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT
    SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
    SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
    OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
    HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
    TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
namespace DVDSwarm
{
    /// <summary>
    /// Progress dialog for demuxing video and audio streams.
    /// </summary>
    public partial class DemuxDvdProgressDialog : Form
    {
        #region Fields

        private Int32 _currentSelectionIndex = -1;
        private string _dvdOutputPath = string.Empty;
        private Boolean _isCanceled = false;
        private PgcdemuxBackgroundWorker _pgcdemux = null;
        private FicSprout.Bacicworx.IO.JobStatus _status = FicSprout.Bacicworx.IO.JobStatus.Inactive;
        private DemuxPgcSelection[] _selections = null;
        private DateTime _startTimestamp = DateTime.Now;
        private Int64 _totalLength = 0;

        #endregion

        #region Properties

        /// <summary>
        /// Sets the DVD output folder where the demuxed video and audio streams are stored.
        /// </summary>
        public string DvdOutputPath
        {
            set
            {
                _dvdOutputPath = value;
            }
        }
        /// <summary>
        /// Sets the selections to demux.
        /// </summary>
        public DemuxPgcSelection[] Selections
        {
            set
            {
                _selections = value;
            }
        }
        /// <summary>
        /// Sets the total length in bytes of the selections.
        /// </summary>
        public Int64 SelectionsLength
        {
            set
            {
                _totalLength = value;
            }
        }

        #endregion

        #region Methods

        /// <summary>
        /// Creats a new instance of the DemuxDvdProgressDialog class.
        /// </summary>
        public DemuxDvdProgressDialog()
        {
            InitializeComponent();

            // Update app icon.
            this.Icon = Properties.Resources.App;
        }

        /// <summary>
        /// Cancels the conversion.
        /// </summary>
        private void CancelDemux()
        {
            if (_isCanceled)
            {
                return;
            }

            _isCanceled = true;

            if (_pgcdemux != null)
            {
                _pgcdemux.Cancel();
            }
        }

        /// <summary>
        /// Finalizes the demux.
        /// </summary>
        private void FinalizeDemux()
        {
            // Required to prevent error: 'Invoke cannot be called until a window handle is created.'
            if (!_isCanceled)
            {
                Invoke(new UpdateCurrentProgressFromThread(UpdateCurrentProgress), new object[] { 100 });
                Invoke(new UpdateEtaFromThread(UpdateEta), new object[] { new FicSprout.Bacicworx.Media.Timecode() });
            }

            _currentSelectionIndex++;

            if (_status == FicSprout.Bacicworx.IO.JobStatus.Completed && _currentSelectionIndex < _selections.Length)
            {
                InitializeDemux();
            }
            else
            {
                DialogResult = System.Windows.Forms.DialogResult.OK;
            }
        }

        /// <summary>
        /// Initializes the demux.
        /// </summary>
        private void InitializeDemux()
        {
            Invoke(new UpdateStreamLabelTextFromThread(UpdateStreamLabelText));
            Invoke(new UpdateCurrentProgressFromThread(UpdateCurrentProgress), new object[] { 0 });
            Invoke(new UpdateTotalProgressFromThread(UpdateTotalProgress), new object[] { _currentSelectionIndex * 100 });
            Invoke(new UpdateEtaFromThread(UpdateEta), new object[] { new FicSprout.Bacicworx.Media.Timecode(0, 1, 0, 0) });
    
            _startTimestamp = DateTime.Now;
            ExecutePgcdemux();
        }

        private delegate void UpdateEtaFromThread(FicSprout.Bacicworx.Media.Timecode value);

        /// <summary>
        /// Required for updating the estimated time remaining from a different thread.
        /// </summary>
        /// <param name="value">The seconds remaining to demux the pgc.</param>
        private void UpdateEta(FicSprout.Bacicworx.Media.Timecode value)
        {
            labelEtaValue.Text = value.ToString("hh:mm:ss");
        }

        private delegate void UpdateCurrentProgressFromThread(Int32 value);

        /// <summary>
        /// Required for updating the current progress bar from a different thread. Range is zero to one hundred.
        /// </summary>
        /// <param name="value">The percentage progress value to display.</param>
        private void UpdateCurrentProgress(Int32 value)
        {
            progressBarCurrent.Value = value;
        }

        private delegate void UpdateStreamLabelTextFromThread();

        /// <summary>
        /// Required for updating the stream label from a different thread.
        /// </summary>
        private void UpdateStreamLabelText()
        {
            if (_currentSelectionIndex == -1)
            {
                return;
            }

            StringBuilder sb = new StringBuilder();
            sb.Append("VTS_" + (_selections[_currentSelectionIndex].Titleset).ToString("00"));
            sb.Append("_PGC_ " + (_selections[_currentSelectionIndex].Pgc).ToString("00"));

            labelStreamValue.Text = sb.ToString();
        }

        private delegate void UpdateTotalProgressFromThread(Int32 value);

        /// <summary>
        /// Required for updating the total progress bar from a different thread.
        /// </summary>
        /// <param name="value">The percentage progress value to display.</param>
        private void UpdateTotalProgress(Int32 value)
        {
            progressBarTotal.Value = value;
        }

        #endregion

        #region Events

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            CancelDemux();
        }

        private void DemuxDvdProgressDialog_Shown(object sender, EventArgs e)
        {
            _currentSelectionIndex = 0;

            progressBarCurrent.Minimum = 0;
            progressBarCurrent.Maximum = 100;
            progressBarCurrent.Value = 0;

            progressBarTotal.Minimum = 0;
            progressBarTotal.Maximum = 100 * _selections.Length;
            progressBarTotal.Value = 0;

            // Enabling and disabling the timer for each job prevents the event
            // from being raised. Set the timer to run continuously.
            timer1.Enabled = true;

            InitializeDemux();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (System.IO.File.Exists(_dvdOutputPath + "\\VideoFile.m2v"))
            {

                System.IO.FileInfo finfo = new System.IO.FileInfo(_dvdOutputPath + "\\VideoFile.m2v");
                if (finfo != null && finfo.Length > 0)
                {
                    Int32 percent = Convert.ToInt32((Convert.ToDouble(finfo.Length) /
                        Convert.ToDouble(_selections[_currentSelectionIndex].VideoLength)) * 100);
                        
                    if (percent > 1)
                    {
                        Int32 millisecondsRemaining = Convert.ToInt32((100 - percent) *
                            (DateTime.Now.Subtract(_startTimestamp).TotalMilliseconds / percent));

                        Invoke(new UpdateCurrentProgressFromThread(UpdateCurrentProgress), new object[] { percent });
                        Invoke(new UpdateTotalProgressFromThread(UpdateTotalProgress), new object[] { 
                            (_currentSelectionIndex * 100) + percent });
                        Invoke(new UpdateEtaFromThread(UpdateEta), new object[] { new FicSprout.Bacicworx.Media.Timecode(
                            0, 0, 0, millisecondsRemaining) });
                    }
                }
            }
        }

        #endregion

        #region Tool Events

        void ExecutePgcdemux_Completed(object sender, EventArgs e)
        {
            _status = _pgcdemux.Status;
            _pgcdemux = null;

            FinalizeDemux();
        }

        #endregion

        #region Tool Methods

        /// <summary>
        /// Runs Pgcdemux to demux the stream.
        /// </summary>
        private void ExecutePgcdemux()
        {
            Invoke(new UpdateStreamLabelTextFromThread(UpdateStreamLabelText));

            _pgcdemux = new PgcdemuxBackgroundWorker(Application.StartupPath + "\\Tools\\pgcdemux.exe",
               _selections[_currentSelectionIndex].IfoFilename, _dvdOutputPath,
               _selections[_currentSelectionIndex]);

            _pgcdemux.Completed += new EventHandler(ExecutePgcdemux_Completed);
            _pgcdemux.Start();
        }

        #endregion
    }
}
