using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using SharpKml.Base;
using SharpKml.Dom;
using SharpKml.Engine;
using System.Windows.Forms;
using System.IO;

using System.Xml.Serialization;
using Point = SharpKml.Dom.Point;


namespace missionPLanning
{
    public partial class MissionPlanner : Form
    {
        List<Placemark> placemarks = new List<Placemark>();

        public MissionPlanner()
        {
            InitializeComponent();
        }

        private void buttonOpenFile_Click(object sender, EventArgs e)
        {
           Stream file = null;
           placemarks.Clear();
           
           OpenFileDialog openFileDialog = new OpenFileDialog();
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    file = openFileDialog.OpenFile();
                }
                catch (Exception ex)
                {

                    MessageBox.Show("Error" + ex.Message);
                }
            }
            else
            {
                return;
            }
            TextReader textReader = new StreamReader(file);
            string xml = textReader.ReadToEnd();
            textReader.Close();
            KmlFile kmlFile;
           
            using (var stream = new MemoryStream(ASCIIEncoding.UTF8.GetBytes(xml)))
            {
                kmlFile = KmlFile.Load(stream);
            }
            Kml kml = kmlFile.Root as Kml;
           
            ExtractPlacemarks(kml.Feature, placemarks);
            AddCustomData();
            updateView();
        }
        private void updateView()
        {
            listViewWaypoints.Items.Clear();
            int id = 0;
            foreach (Placemark placemark in placemarks)
            {
                placemark.Id = id.ToString();
                id += 1;
                ListViewItem listViewItem = new ListViewItem(placemark.Id);
                Point point = placemark.Geometry as Point;
                listViewItem.SubItems.Add(placemark.Name);
                listViewItem.SubItems.Add(point.Coordinate.Latitude.ToString());
                listViewItem.SubItems.Add(point.Coordinate.Longitude.ToString());
                listViewItem.Tag = placemark;
                listViewWaypoints.Items.Add(listViewItem);
            }
        }
        private void listViewWaypoints_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (listViewWaypoints.SelectedItems.Count > 0)
            {
                Placemark selected = (Placemark)listViewWaypoints.SelectedItems[0].Tag;
                foreach (Data data in selected.ExtendedData.Data)
                {
                    if (data.Name == "speed")
                    {
                        textBoxSpeed.Text = data.Value;
                    }
                    if (data.Name == "depth")
                    {
                        textBoxDepth.Text = data.Value;
                    }                    
                }
                textBoxID.Text = selected.Id;
            }

        }

        private void buttonSave_Click(object sender, EventArgs e)
        {
            Placemark placemark = placemarks.Find(p => p.Id == textBoxID.Text);
            foreach (Data data in placemark.ExtendedData.Data)
            {
                if (data.Name == "speed")
                {
                    data.Value = textBoxSpeed.Text;                    
                }
                if (data.Name == "depth")
                {
                    data.Value = textBoxDepth.Text;                    
                }
            }
            updateView();
        }

        private void buttonSaveFile_Click(object sender, EventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "kml files (*.kml)|*.kml|All files (*.*)|*.*";
            saveFileDialog.FilterIndex = 2;
            saveFileDialog.RestoreDirectory = true;
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                    StreamWriter myStream = new StreamWriter(saveFileDialog.FileName);
                    myStream.Write(GenerateLines());
                    myStream.Close();
            }                        
        }

        private string GenerateLines()
        {
            Kml kml = new Kml();            
            Document document = new Document();            
            Folder folderMission = new Folder();
            kml.Feature = document;
            folderMission.Name = "mission";
            document.AddFeature(folderMission);

            //initialization
            bool firstIteration = true;
            Placemark previous = placemarks.First();           
            foreach (Placemark placemark in placemarks)
            {
                if (firstIteration)
                {
                    firstIteration = false;
                }
                else
                {
                    LineString ls = new LineString();
                    Point previousPoint = previous.Geometry as Point;
                    Point currentPoint = placemark.Geometry as Point;
                    CoordinateCollection coordinateCollection = new CoordinateCollection();

                    coordinateCollection.Add(new Vector(previousPoint.Coordinate.Latitude, previousPoint.Coordinate.Longitude));                    
                    coordinateCollection.Add(new Vector(currentPoint.Coordinate.Latitude, currentPoint.Coordinate.Longitude));
                    ls.Coordinates = coordinateCollection;

                    previous.Geometry = ls;                    
                    Feature feature = previous.Clone();
                    folderMission.AddFeature(feature);
                    previous = placemark;
                } 
            }
            Serializer serializer = new Serializer();
            serializer.Serialize(kml);
            Console.WriteLine(serializer.Xml);
            return serializer.Xml;
        }

        private void AddCustomData()
        {
            foreach (Placemark placemark in placemarks)
            {
                Data dataSpeed = new Data {DisplayName = "speed", Name = "speed", Value = "0"};
                Data dataDepth = new Data {DisplayName = "depth", Name = "depth", Value = "0"};
                ExtendedData extendedData = new ExtendedData();
                extendedData.AddData(dataSpeed);
                extendedData.AddData(dataDepth);
                placemark.ExtendedData = extendedData;                
            }
        }

        private void ExtractPlacemarks(Feature feature, List<Placemark> placemarks)
        {            
            Placemark placemark = feature as Placemark;
            if (placemark != null)
            {
                placemarks.Add(placemark);
            }
            else
            {               
                SharpKml.Dom.Container container = feature as SharpKml.Dom.Container;
                if (container != null)
                {                    
                    foreach (var f in container.Features)
                    {
                        ExtractPlacemarks(f, placemarks);
                    }
                }
            }
        }
    }
}
