using Demo.RadMap.UI.Tools;
using System;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.Windows.Media;
using Vishcious.ArcGIS.SLContrib;
using Telerik.Windows.Controls.Map;
using System.Net;
using System.Collections.ObjectModel;

namespace Demo.RadMap.UI
{
    public partial class MainPage : UserControl
    {
        private StyleSettings style = new StyleSettings() { Fill = new SolidColorBrush(Colors.Yellow), StrokeColor = Colors.Black, StrokeThickness = 1f }; // todo: create style builder
        private System.Collections.ObjectModel.Collection<ShapeFileRecord> records;
        private Stream dbfStream;
        private Stream shapeStream;
        private ObservableCollection<string> history = new ObservableCollection<string>();
        private MapShape currentSelectedShape;

        public MainPage()
        {
            InitializeComponent();

            this.eventList.ItemsSource = history;
        }

        private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
        {
            try
            {
                OpenFileDialog ofd = new OpenFileDialog();
                ofd.Multiselect = true;

                if (!(ofd.ShowDialog() ?? false))
                    return;

                FileInfo shapeFile = ofd.Files.FirstOrDefault(f => f.Extension.ToLower() == ".shp");
                FileInfo dbfFile = ofd.Files.FirstOrDefault(f => f.Extension.ToLower() == ".dbf");


                if (shapeFile == null || dbfFile == null)
                {
                    HtmlPage.Window.Alert("Please select a SHP and a DBF file to proceed.");
                    return;
                }

                ShapeFile shapeFileReader = new ShapeFile();
                shapeFileReader.Read(shapeFile, dbfFile);

                LoadShapes(shapeFileReader.Records);
            }
            catch (Exception ex)
            {
                HtmlPage.Window.Alert(ex.Message);
            }
        }

        private void LoadShapes(Collection<ShapeFileRecord> shapes)
        {
            InformationLayer.Items.Clear();

            records = shapes;

            var mapShapes = shapes.ToMapElements();

            mapShapes.ToList().ForEach(element =>
            {
                var mapShape = element as MapShape;

                if (mapShape != null)
                {
                    mapShape.Fill = style.Fill;
                    mapShape.StrokeThickness = style.StrokeThickness;
                    mapShape.Stroke = new SolidColorBrush(style.StrokeColor);

                    mapShape.CacheMode = new BitmapCache();

                    mapShape.MouseEnter += (sender, e) =>
                    {
                        var shapeRecord = GetShapeRecord(sender);
                        AddToHistory(shapeRecord, "Mouse Enter");
                    };

                    mapShape.MouseLeave += (sender, e) =>
                    {
                        var shapeRecord = GetShapeRecord(sender);
                        AddToHistory(shapeRecord, "Mouse Leave");
                    };

                    mapShape.MouseLeftButtonUp += (sender, e) =>
                    {
                        if (currentSelectedShape != null)
                            currentSelectedShape.Fill = style.Fill;

                        mapShape.Fill = new SolidColorBrush(Colors.Magenta);

                        var shapeRecord = GetShapeRecord(sender);
                        AddToHistory(shapeRecord, "Click");

                        currentSelectedShape = mapShape;
                    };
                }

                InformationLayer.Items.Add(element);
            });
        }

        private void AddToHistory(ShapeFileRecord shapeRecord, string action)
        {
            var firstAttribute = string.Empty;

            if (shapeRecord != null && shapeRecord.Attributes != null && shapeRecord.Attributes.Keys.Count > 0)
            {
                firstAttribute = shapeRecord.Attributes[shapeRecord.Attributes.Keys.First().ToString()].ToString().Trim();
            }

            history.Insert(0, string.Format("{0} {1}", firstAttribute, action));
            
        }

        private ShapeFileRecord GetShapeRecord(object s)
        {
            var shapeRecord = (ShapeFileRecord)((MapShape)s).Tag;
            return shapeRecord;
        }

        private void mapProvider_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (myMap != null)
            {
                var selectedItem = ((ComboBoxItem)this.mapProvider.SelectedItem).Content;
                if (selectedItem.Equals("Empty"))
                {
                    myMap.Provider = new EmptyProvider();
                }
                else
                {
                    myMap.Provider = new OpenStreetMapProvider();
                }
            }
        }
    }
}
