using System;
using System.IO;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Navigation;
using Microsoft.Surface;
using Microsoft.Surface.Presentation;
using Microsoft.Surface.Presentation.Controls;
using System.Collections.Generic;
using System.Windows.Media.Imaging;
using System.Xml.Serialization;
using System.Reflection;
using FingersDance.Control;

namespace FingersDance.Control.ListVideo
{
    public partial class UserControlListVideo
    {
        //Creation d'un Event pour Chaque Item Video
        public event EventHandler EH_ItemVideo1_ContactDown;

        public string path = "";
        public string VideoName = "";
        
        public UserControlListVideo()
        {
            this.InitializeComponent();
            UpdateList();

            // Insert code required on object creation below this point.
        }

        //Event appelé lors de la selection d'un Item dans la Video List
        private void ItemVideo_ContactTapGesture(object sender, Microsoft.Surface.Presentation.ContactEventArgs e)
        {
            path = ((CustomListBoxItem)sender).Path;
            VideoName = path;
            if (EH_ItemVideo1_ContactDown != null)
                EH_ItemVideo1_ContactDown(this, new EventArgs());
            
        }

        private void ItemVideo_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            path = ((CustomListBoxItem)sender).Path;
            VideoName = path;
            if (EH_ItemVideo1_ContactDown != null)
                EH_ItemVideo1_ContactDown(this, new EventArgs());

        }

        private void ButtonImporter_ContactDown(object sender, Microsoft.Surface.Presentation.ContactEventArgs e)
        {
            AddVideoToList();
        }

        private void ButtonImporter_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            AddVideoToList();
        }

        private void AddVideoToList()
        {
            try
            {
                Dictionary<string, ListVideoItem> _Videos = (new ListVideo()).GetVideos();
                string[] Files = new string[1];
                if (System.IO.Directory.Exists(PathImporter.Text))
                    Files = System.IO.Directory.GetFiles(PathImporter.Text);
                else
                    if (System.IO.File.Exists(PathImporter.Text))
                        Files[0] = PathImporter.Text;
                if (Files != null)
                {
                    foreach (string elt in Files)
                        if (elt.ToLower().EndsWith(".wmv")) // .....
                            try
                            {
                                ListVideoItem newItem = new ListVideoItem();
                                Image item = getFirstPreview(elt);
                                if (item != null && !_Videos.ContainsKey(elt))
                                {
                                    newItem.Name = elt.Split('\\')[elt.Split('\\').Length - 1].Split('.')[0];
                                    newItem.Path = elt;
                                    newItem.Preview = elt.Replace(".wmv", ".jpg");
                                    _Videos.Add(newItem.Path, newItem);
                                }
                            }
                            catch (Exception ex) { }
                    UpdateList();
                    SaveList();
                }
            }
            catch (Exception) { }
        }

        Image getFirstPreview(string path)
        {
            MediaPlayer _player = new MediaPlayer();
            _player.Open(new Uri(path));
            _player.Play();
            _player.Position = new TimeSpan(0, 0, 5);
            System.Threading.Thread.Sleep(800);
            RenderTargetBitmap target = new RenderTargetBitmap(100, 100, 1 / 100, 1 / 100, PixelFormats.Pbgra32);
            DrawingVisual visual = new DrawingVisual();
            DrawingContext context = visual.RenderOpen();
            Rect frameRect = new Rect();
            frameRect.Height = target.Height;
            frameRect.Width = target.Width;
            context.DrawVideo(_player, frameRect);
            context.Close();
            target.Render(visual);
            Image _prev = new Image();
            _prev.Source = BitmapFrame.Create(target).GetAsFrozen() as BitmapFrame;
            _player.Stop();

            return _prev;
        }

        private void RefreshButton_ContactDown(object sender, Microsoft.Surface.Presentation.ContactEventArgs e)
        {
            UpdateList();
        }

        private void RefreshButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            UpdateList();
        }

        

        void SaveList()
        {
            Dictionary<string, ListVideoItem> _Videos = (new ListVideo()).GetVideos();
            StreamWriter writter = null;
            FileInfo assemblyPath = new FileInfo(Assembly.GetExecutingAssembly().Location);
            DirectoryInfo info = assemblyPath.Directory;
            try
            {
                writter = new StreamWriter(info.FullName.ToString() + "\\Resources\\videos.xml");
                XmlSerializer serializer = new XmlSerializer(typeof(List<ListVideoItem>));
                List<ListVideoItem> temp = new List<ListVideoItem>();
                foreach (KeyValuePair<string, ListVideoItem> elt in _Videos)
                    temp.Add(elt.Value);
                serializer.Serialize(writter, temp);
                writter.Close();
            }
            catch (Exception e)
            {
                if (writter != null)
                    writter.Close();
            }
        }

        void UpdateList()
        {
            Dictionary<string, ListVideoItem> _Videos = (new ListVideo()).GetVideos();
            stackPanel.Children.Clear();
            foreach (KeyValuePair<string, ListVideoItem> elt in _Videos)
            {
                try
                {
                    if (!elt.Value.Preview.Equals(""))
                    {
                        MediaElement item = new MediaElement();
                        item.Source = new Uri(elt.Value.Preview);
                        item.Width = 100;
                        item.Height = 100;
                        CustomListBoxItem Contener = new CustomListBoxItem();
                        Contener.Content = item;
                        Contener.Path = elt.Value.Path;
                        Contener.Name = elt.Value.Name;
                        Contener.ContactTapGesture += ItemVideo_ContactTapGesture;
                        stackPanel.Children.Add(Contener);
                    }
                }
                catch (Exception e)
                { }
            }
        }

        private void SurfaceRadioButton_ContactDown(object sender, Microsoft.Surface.Presentation.ContactEventArgs e)
        {
            if (Import_video_Container.Visibility == Visibility.Collapsed)
            {
                Import_video_Container.Visibility = Visibility.Visible;
            }

            else if (Import_video_Container.Visibility == Visibility.Visible)
            {
                Import_video_Container.Visibility = Visibility.Collapsed;
            }
			// TODO: Add event handler implementation here.
        }

        private void SurfaceRadioButton_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            if (Import_video_Container.Visibility == Visibility.Collapsed)
            {
                Import_video_Container.Visibility = Visibility.Visible;
            }

            else if (Import_video_Container.Visibility == Visibility.Visible)
            {
                Import_video_Container.Visibility = Visibility.Collapsed;
            }
			// TODO: Add event handler implementation here.
        }
    }
}