using System;
using System.IO;
using System.Net;
using System.Collections.Generic;
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 System.Xml.Linq;
using FingersDance.Control.ListVideo;
using FingersDance.Control.SessionInput;
using FingersDance.ViewModels;
using FingersDance.Data;

namespace FingersDance.Control.Screen
{
	public partial class UserControlScreen
	{
        public String contexteGrid;
        public int id = 0;
        public event EventHandler UC_Screen_NewCutting;
        private MainViewModel _mainViewModel;
        public Cutting Cutting;

        private String videoName;
        private String videoPath;

        User User = new User();

        public UserControlScreen(int id, MainViewModel mvmodel)
        {
            try
            {
                this.InitializeComponent();
                this.id = id;
                User.Name = "User " + id;
                _mainViewModel = mvmodel;
                if (_mainViewModel.Project.VideoPath.Equals(""))
                {
                    //1-Creation de la ListVideo
                    UserControlListVideo ListVideo = new UserControlListVideo();
                    ListVideo.Name = "ListVideo1";
                    //2-Ajout de la ListVideo au ControlScreen
                    this.AddToGrid(ListVideo);
                    //3-Creation des Events pour chaque item de la video
                    ListVideo.EH_ItemVideo1_ContactDown += new System.EventHandler(ListVideo_EH_ItemVideo_ContactDown);
                }
                else
                    OpenProject();
            }
            catch (Exception)
            {
                Cutting = null;
                if (UC_Screen_NewCutting != null)
                    UC_Screen_NewCutting(this, new EventArgs());
            }
        }

        //Rajout un UIElement vers la grid du screen.
        public void AddToGrid(UIElement uie)
        {
            if (uie != null)
            {
                try { LayoutRoot.Children.Add(uie); }
                catch(Exception){}
            }          
        }

        private void ListVideo_EH_ItemVideo_ContactDown(object sender, EventArgs e)
        {
            try
            {
                //1 renseigner la video choisie au screen et créer un nouveau projet à partir de ce chemin vidéo
                videoName = ((UserControlListVideo)sender).VideoName;
                videoPath = ((UserControlListVideo)sender).path;
                _mainViewModel.CreateProject(videoName, videoPath);
                //2-Supression du UC List Video
                LayoutRoot.Children.Remove((UserControlListVideo)sender);
                OpenProjectList();
            }
            catch (Exception ex)
            {
                Cutting = null;
                if (UC_Screen_NewCutting != null)
                    UC_Screen_NewCutting(this, new EventArgs());
            }
        }

        private void OpenProjectList()
        {
            try
            {
                // We get all the ldt/project files from the current directory...
                List<String> existingProjects = new List<String>();
                foreach (String filename in Directory.GetFiles("./"))
                {
                    if (filename.Substring(filename.Length-4).ToLower()==".ldt")
                        existingProjects.Add(filename.Substring(2, filename.Length - 6));
                }
                // ... and display them the the select box UserControlListProject
                UserControlListProject listProject = new UserControlListProject(existingProjects);
                listProject.Name = "ListProject";
                LayoutRoot.Children.Add(listProject);
                listProject.EH_ListProject_ContactDown += new EventHandler(listProject_EH_ListProject_ContactDown);
            }
            catch (Exception)
            {
                Cutting = null;
                if (UC_Screen_NewCutting != null)
                    UC_Screen_NewCutting(this, new EventArgs());
            }
        }

        void listProject_EH_ListProject_ContactDown(object sender, EventArgs e)
        {
            try
            {
                LayoutRoot.Children.Remove((UserControlListProject)sender);
                if (((UserControlListProject)sender).SelectedItem.Equals("New Project"))
                {
                    UserControlNewProjectForm ProjectInput = new UserControlNewProjectForm();
                    ProjectInput.Name = "ProjectInput";
                    LayoutRoot.Children.Add(ProjectInput);
                    ProjectInput.EH_NewProjectForm_ContactDown += new System.EventHandler(this.ProjectInput_EH_NewProjectForm_ContactDown);
                }
                else
                {
                    // ((UserControlListProject)sender).SelectedItem is the name of the selected project
                    // Now we load the xml/ldt file to load all its datas (cuttings, annotations...)
                    XDocument loadedLdt = XDocument.Load(((UserControlListProject)sender).SelectedItem + ".ldt");
                    Project loadedProject = new Project(videoName, videoPath);
                    loadedProject.Name = loadedLdt.Root.Element("project").Attribute("title").Value;
                    loadedProject.Description = loadedLdt.Root.Element("project").Attribute("abstract").Value;
                    loadedProject.Cuttings = new List<Cutting>();
                    XElement cuttingsParentNode = loadedLdt.Root.Element("annotations").Element("content");
                    foreach (XElement cuttingNode in cuttingsParentNode.Elements())
                    {
                        List<Annotation> la = new List<Annotation>();
                        foreach (XElement annotNode in cuttingNode.Element("elements").Elements())
                        {
                            String aId = annotNode.Attribute("id").Value;
                            float begin = (float)annotNode.Attribute("begin");
                            float dur = (float)annotNode.Attribute("dur");
                            String gt = annotNode.Element("gestureType").Value;
                            String colorString = annotNode.Attribute("color").Value; // is type 0xRRGGBB
                            Byte r = Convert.ToByte(colorString.Substring(2, 2), 16);
                            Byte g = Convert.ToByte(colorString.Substring(4, 2), 16);
                            Byte b = Convert.ToByte(colorString.Substring(6, 2), 16);
                            Color c = Color.FromRgb(r, g, b);
                            la.Add(new Annotation(aId, begin, dur, gt, c));
                        }
                        loadedProject.Cuttings.Add(new Cutting(cuttingNode.Attribute("id").Value,cuttingNode.Element("title").Value,la));
                    }
                    // We define the loaded project as the current session's project.
                    _mainViewModel.Project = new ProjectViewModel(loadedProject);
                    OpenProject();
                }
            }
            catch (Exception)
            {
                Cutting = null;
                if (UC_Screen_NewCutting != null)
                    UC_Screen_NewCutting(this, new EventArgs());
            }
        }

        private void ProjectInput_EH_NewProjectForm_ContactDown(object sender, EventArgs e)
        {
            try
            {
                //MainViewModel.Project.Alias = ((UserControlNewProjectForm)sender).Alias;
                //MainViewModel.Project.Email = ((UserControlNewProjectForm)sender).Email;
                _mainViewModel.Project.Description = ((UserControlNewProjectForm)sender).Description;
                _mainViewModel.Project.Name = ((UserControlNewProjectForm)sender).ProjectName.Trim();
                
                
                //2-Suppression UCSession Input
                LayoutRoot.Children.Remove((UserControlNewProjectForm)sender);
                OpenProject();
            }
            catch (Exception ex) 
            {
                Cutting = null;
                if (UC_Screen_NewCutting != null)
                    UC_Screen_NewCutting(this, new EventArgs());
            }
        }

        private void OpenProject()
        {
            try
            {
                // We display the list of cuttings available for the current project
                UserControlListCutting listCuttings = new UserControlListCutting(_mainViewModel.Project.CuttingsDict);
                listCuttings.Name = "listCuttings";
                LayoutRoot.Children.Add(listCuttings);
                listCuttings.EH_Item_ContactDown += new EventHandler(listCuttings_EH_Item_ContactDown);
            }
            catch (Exception) 
            {
                Cutting = null;
                if (UC_Screen_NewCutting != null)
                    UC_Screen_NewCutting(this, new EventArgs());
            }
        }

        void listCuttings_EH_Item_ContactDown(object sender, EventArgs e)
        {
            try
            {
                LayoutRoot.Children.Remove((UserControlListCutting)sender);
                if (((UserControlListCutting)sender).SelectedItem.Equals("New Cutting"))
                {
                    // "New Uutting" was was selected -> we display the form
                    UserControlNewCuttingForm newCutting = new UserControlNewCuttingForm(User);
                    newCutting.Name = "newCutting";
                    LayoutRoot.Children.Add(newCutting);
                    newCutting.EH_NewCuttingForm_ContactDown += new EventHandler(newCutting_EH_ContactDown);
                }
                else
                {
                    // An already existing project was clicked -> we load the selected project from the dictionnary
                    Cutting = _mainViewModel.Project.CuttingsDict[((UserControlListCutting)sender).SelectedItem];
                    if (UC_Screen_NewCutting != null)
                        UC_Screen_NewCutting(this, new EventArgs());
                    return;
                }
            }
            catch (Exception)
            {
                Cutting = null;
                if (UC_Screen_NewCutting != null)
                    UC_Screen_NewCutting(this, new EventArgs());
            }
        }

        void newCutting_EH_ContactDown(object sender, EventArgs e)
        {
            try
            {
                LayoutRoot.Children.Remove((UserControlNewCuttingForm)sender);
                // The new cutting form sent the cutting instance so we can dispatch the event UC_Screen_NewCutting
                Cutting = ((UserControlNewCuttingForm)sender).Cutting;
                if (UC_Screen_NewCutting != null)
                    UC_Screen_NewCutting(this, new EventArgs());
            }
            catch (Exception)
            {
                Cutting = null;
                if (UC_Screen_NewCutting != null)
                    UC_Screen_NewCutting(this, new EventArgs());
            }
        }
	}
}