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;
using FingersDance.Factory;

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 String AnnotationOrSearchMode;
        public Project SearchedProject;
        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
                    GetAnnotationOrSearchMode();
            }
            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;
                // We initialize it in _mainViewModel for it to remembered in every place of the application
                _mainViewModel.Project.VideoPath = videoPath;
                // 2-Supression du UC List Video
                LayoutRoot.Children.Remove((UserControlListVideo)sender);
                // 3 - Choose between Annotation Or Search Mode
                GetAnnotationOrSearchMode();
                //OpenProjectList();
            }
            catch (Exception ex)
            {
                Cutting = null;
                if (UC_Screen_NewCutting != null)
                    UC_Screen_NewCutting(this, new EventArgs());
            }
        }

        private void GetAnnotationOrSearchMode()
        {
            UserControlAnnotationOrSearch AnnotOrSearch = new UserControlAnnotationOrSearch();
            AnnotOrSearch.ModeChosen += new EventHandler<AnnotationOrSearchEventArg>(AnnotOrSearch_ModeChosen);
            this.AddToGrid(AnnotOrSearch);
        }

        void AnnotOrSearch_ModeChosen(object sender, AnnotationOrSearchEventArg e)
        {
            // We remove the UserControlAnnotationOrSearch
            LayoutRoot.Children.Remove((UserControlAnnotationOrSearch)sender);
            // We show the project list and send the chosen mode
            AnnotationOrSearchMode = e.ChosenMode;
            if (AnnotationOrSearchMode == "Annotation" && _mainViewModel.Project.Cuttings.Count!=0)
                OpenProject();
            else
                OpenProjectList();

        }

        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, AnnotationOrSearchMode);
                    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, _mainViewModel.Project.VideoPath); // we use this video in the case an other panel was in search mode before annotation mode
                    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");
                    DataDictionary Data = (new DataFactory()).Data;
                    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);
                            Annotation Annotation = new Annotation(aId, begin, dur, gt, c);
                            la.Add(Annotation);
                            Data.AddAnnotation(Annotation);
                        }
                        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 in annotation mode or the searched project in search mode
                    if (AnnotationOrSearchMode == "Annotation")
                        _mainViewModel.Project = new ProjectViewModel(loadedProject);
                    else
                        SearchedProject = 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
            {
                if (AnnotationOrSearchMode == "Annotation")
                {
                    // 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);
                }
                else
                {
                    Cutting = null;
                    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());
            }
        }

        void listCuttings_EH_Item_ContactDown(object sender, EventArgs e)
        {
            try
            {
                LayoutRoot.Children.Remove((UserControlListCutting)sender);
                if (((UserControlListCutting)sender).SelectedItem.Equals("New Cutting"))
                {
                    // "New Cutting" 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());
            }
        }
	}
}