using SkmXmlApi;
using System;
using System.Threading;
using System.Windows.Forms;

namespace PlayerTestNET
{
    public partial class SaveVideoDialog : Form
    {
        private Camera m_Camera;
        private string m_FileName;
        private DownloadTask m_Task;

        public SaveVideoDialog()
        {
            InitializeComponent();
        }

        public DialogResult ShowSaveDialog(string cameraId)
        {
            // An Skm session must be created first and login performed.
            SkmSession session = SkmSession.NewSkmSession(MainForm.ServerUrl);
            session.Login(MainForm.Username, MainForm.Password);

            // Create credential command to get camera object.
            var cc = CredentialCommand.NewCredentialCommand(session);
            m_Camera = cc.Cameras.Find(cam => cam.Id.ToString() == cameraId);
            if (m_Camera == null)
            {
                MessageBox.Show("Camera is not found.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return DialogResult.Cancel;
            }

            using (var saveFileDlg = new SaveFileDialog())
            {
                saveFileDlg.Filter = "QuickTime Video (*.mov)|*.mov";
                if (saveFileDlg.ShowDialog() != DialogResult.OK)
                {
                    return DialogResult.Cancel;
                }
                m_FileName = saveFileDlg.FileName;
                tbFileName.Text = m_FileName;
            }

            dtStartTime.Value = DateTime.Now.AddSeconds(-90);
            dtEndTime.Value = DateTime.Now.AddSeconds(-60);

            m_Camera.DownloadMediaClipProgress += Camera_DownloadMediaClipProgress;

            return ShowDialog();
        }

        private void OnDownloadProgress(DownloadProgressEventArgs e)
        {
            switch (e.Status)
            {
                case DownloadStatus.InProgress:
                    pbProgress.Value = e.Progress;
                    break;
                case DownloadStatus.Done:
                    m_Task = null;
                    pbProgress.Value = 100;
                    MessageBox.Show("Media clip successfully downloaded.", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    DialogResult = DialogResult.OK;
                    break;
                case DownloadStatus.Error:
                    m_Task = null;
                    pbProgress.Value = 0;
                    MessageBox.Show(e.Exception != null ? e.Exception.Message : "Unknown error.", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    break;
            }
            btSave.Enabled = m_Task == null;
        }

        private void Camera_DownloadMediaClipProgress(object sender, DownloadProgressEventArgs e)
        {
            if (InvokeRequired)
            {
                BeginInvoke((ThreadStart) delegate { OnDownloadProgress(e); });
                return;
            }
            OnDownloadProgress(e);
        }

        private void btSave_Click(object sender, EventArgs e)
        {
            m_Task = m_Camera.StartDownloadMediaClip(m_FileName, dtStartTime.Value.ToUniversalTime(), dtEndTime.Value.ToUniversalTime());
            btSave.Enabled = false;
        }

        private void btCancel_Click(object sender, EventArgs e)
        {
            if (m_Task != null)
            {
                m_Task.CancellationToken.Cancel();
                m_Task = null;
                pbProgress.Value = 0;
                btSave.Enabled = true;
                return;
            }
            DialogResult = DialogResult.Cancel;
        }

        private void SaveVideoDialog_FormClosed(object sender, FormClosedEventArgs e)
        {
            if (m_Camera != null)
            {
                m_Camera.DownloadMediaClipProgress -= Camera_DownloadMediaClipProgress;
            }
            if (m_Task != null)
            {
                m_Task.CancellationToken.Cancel();
                m_Task = null;
            }
        }
    }
}
