using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;
using Microsoft.Win32.SafeHandles;
using System.Threading;
using System.Diagnostics;

namespace Sample8_PlayEncryptedVideo
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
        }

        private void buttonEncrypt_Click(object sender, EventArgs e)
        {
            EncryptVideoForm EncryptVideoForm = new EncryptVideoForm();
            EncryptVideoForm.ShowDialog();

            if (EncryptVideoForm.AskedToPlay)
            { 
                PlayEncryptedVideo(EncryptVideoForm.EncryptedFilePath);
            }
        }

        private void buttonPlay_Click(object sender, EventArgs e)
        {
            Logger.Log(string.Format("buttonPlay_Click, thread = {0}", Thread.CurrentThread.ManagedThreadId));

            OpenFileDialog dlg = new OpenFileDialog();

            if (dlg.ShowDialog() == DialogResult.OK)
            {
                PlayEncryptedVideo(dlg.FileName);
            }
        }

        private void PlayEncryptedVideo(string path)
        {
            using (SafeFileHandle fileHandle =
               new SafeFileHandle(
                   BoxedAppSDK.NativeMethods.BoxedAppSDK_CreateVirtualFileBasedOnIStream(
                       @"1.avi", // name of the pseudo file
                       BoxedAppSDK.NativeMethods.EFileAccess.GenericWrite,
                       BoxedAppSDK.NativeMethods.EFileShare.Read,
                       IntPtr.Zero,
                       BoxedAppSDK.NativeMethods.ECreationDisposition.New,
                       BoxedAppSDK.NativeMethods.EFileAttributes.Normal,
                       IntPtr.Zero,
                       new VirtualFileStream(path)
                   ),
                   true
               )
           )
            {
                // We use "using" to close the allocated handle
                // The virtual file will still exist
            }

            axWindowsMediaPlayer1.URL = @"1.avi";
        }
   }
}