using System;
using System.Collections.Generic;
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 DVD program chains.
    /// </summary>
    public partial class DemuxDvdProgressDialog : Form
    {
        #region Fields

        private Dvd.IfoReader _dvd = null;
        private Dvd.DemuxerBackgroundWorker _dvdDemuxerBackgroundWorker = null;
        private string _dvdDemuxerOutputPath = string.Empty;
        private Boolean _cancel = false;
        private JobStatus _status = JobStatus.Inactive;
        
        #endregion

        #region Properties

        /// <summary>
        /// Gets a list of programs that have damaged packets. If none were detected, an empty
        /// list is returned.
        /// </summary>
        public List<string> DamagedPrograms
        {
            get
            {
                return _dvdDemuxerBackgroundWorker.DamagedPrograms;
            }
        }
        /// <summary>
        /// Gets the demuxing status.
        /// </summary>
        public JobStatus Status
        {
            get
            {
                return _status;
            }
        }
   
        #endregion

        #region Methods

        /// <summary>
        /// Creats a new instance of the DemuxDvdProgressDialog class.
        /// </summary>
        /// <param name="dvd">The DVD info.</param>
        /// <param name="path">The DVD demuxer output folder.</param>
        /// <exception cref="System.ArgumentNullException">Thrown when dvd is null.</exception>
        /// <exception cref="System.IO.DirectoryNotFoundException">Thrown when path is not found.</exception>
        public DemuxDvdProgressDialog(Dvd.IfoReader dvd, string path)
        {
            if (dvd == null)
            {
                throw new ArgumentNullException("dvd");
            }
            if (string.IsNullOrEmpty(path))
            {
                throw new ArgumentException("path is null or empty.");
            }
            if (!System.IO.Directory.Exists(path))
            {
                throw new System.IO.DirectoryNotFoundException("'" + path + "' not found.");
            }

            InitializeComponent();

            // Update app icon.
            this.Icon = Properties.Resources.App;
            _dvd = dvd;
            _dvdDemuxerOutputPath = path;
        }

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

            _cancel = true;

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

        private delegate void UpdateEtaFromThread(Dvd.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(Dvd.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 (_dvdDemuxerBackgroundWorker.Status == JobStatus.Active)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("Title " + (_dvdDemuxerBackgroundWorker.TitleSet).ToString("00"));
                sb.Append(", Program " + (_dvdDemuxerBackgroundWorker.ProgramChain).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 buttonPause_Click(object sender, EventArgs e)
        {
            _dvdDemuxerBackgroundWorker.Pause();

            // Update button text based on Pause state.
            if (_dvdDemuxerBackgroundWorker.Paused)
            {
                timer1.Enabled = false;
                buttonPause.Text = "Resume";
            }
            else
            {
                timer1.Enabled = true;
                buttonPause.Text = "Pause";
            }
        }

        private void DemuxDvdProgressDialog_Shown(object sender, EventArgs e)
        {
            progressBarCurrent.Minimum = 0;
            progressBarCurrent.Maximum = 100;
            progressBarCurrent.Value = 0;

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

            ExecuteDemuxer();
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            // Only update if progress percent is at least one percent.
            if (_dvdDemuxerBackgroundWorker.ProgramChainProgress > 1)
            {
                Invoke(new UpdateStreamLabelTextFromThread(UpdateStreamLabelText));
                Invoke(new UpdateCurrentProgressFromThread(UpdateCurrentProgress), new object[] {
                    _dvdDemuxerBackgroundWorker.ProgramChainProgress });

                Invoke(new UpdateTotalProgressFromThread(UpdateTotalProgress), new object[] { 
                    _dvdDemuxerBackgroundWorker.TotalProgress });
                Invoke(new UpdateEtaFromThread(UpdateEta), new object[] {
                    _dvdDemuxerBackgroundWorker.ProgramChainTimeRemaining });
            }
        }

        #endregion

        #region Tool Events

        void ExecuteDemuxer_Completed(object sender, EventArgs e)
        {
            timer1.Enabled = false;

            _status = _dvdDemuxerBackgroundWorker.Status;

            // Required to prevent error: 'Invoke cannot be called until a window handle is created.'
            if (!_cancel)
            {
                Invoke(new UpdateCurrentProgressFromThread(UpdateCurrentProgress), new object[] { 100 });
                Invoke(new UpdateEtaFromThread(UpdateEta), new object[] { new Dvd.Timecode() });
            }

            DialogResult = System.Windows.Forms.DialogResult.OK;
        }

        #endregion

        #region Tool Methods

        /// <summary>
        /// Runs the demuxer.
        /// </summary>
        private void ExecuteDemuxer()
        {
            _dvdDemuxerBackgroundWorker = new DVDSwarm.Dvd.DemuxerBackgroundWorker(_dvd, _dvdDemuxerOutputPath);
            _dvdDemuxerBackgroundWorker.Completed += new EventHandler(ExecuteDemuxer_Completed);
            _dvdDemuxerBackgroundWorker.Start();
         
            Invoke(new UpdateStreamLabelTextFromThread(UpdateStreamLabelText));
            Invoke(new UpdateCurrentProgressFromThread(UpdateCurrentProgress), new object[] { 0 });
            Invoke(new UpdateTotalProgressFromThread(UpdateTotalProgress), new object[] { 0 });
            Invoke(new UpdateEtaFromThread(UpdateEta), new object[] { new Dvd.Timecode(0, 1, 0, 0) });
         
            timer1.Enabled = true;
        }

        #endregion
    }
}
