using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.ServiceModel;
using System.IO;
using System.Xml.Linq;
using Microsoft.VirtualEarth.MapControl;
using System.Globalization;

namespace Maps
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            mapa.Children.Clear();
            

            Area a = (Area)cboAreas.SelectedItem;

            string polygonText = a.Polygon.Substring(10, a.Polygon.Length - 12);

            string[] coordinates = polygonText.Split(new char[] {','});
            
            MapPolygon polygon = new MapPolygon();
            polygon.Fill = new SolidColorBrush(Colors.Red);
            polygon.Stroke = new SolidColorBrush(Colors.Yellow);
            polygon.StrokeThickness = 2;
            polygon.Opacity = 0.6;
            polygon.Locations = new LocationCollection();

            foreach (string coordinate in coordinates)
            {
                int i = coordinate.Trim().IndexOf(' ');
                Location l = new Location();
                l.Latitude = Double.Parse(coordinate.Substring(0, i).Trim(), CultureInfo.InvariantCulture.NumberFormat);
                l.Longitude = Double.Parse(coordinate.Substring(i + 1).Trim(), CultureInfo.InvariantCulture.NumberFormat);

                polygon.Locations.Add(l);
            }

            mapa.AddChild(polygon);
        }

        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(new Uri("http://localhost:54850/Areas.ashx"));
            request.BeginGetResponse(OnData, request);
        }

        private void OnData(IAsyncResult e)
        {
            HttpWebRequest request = (HttpWebRequest)e.AsyncState;
            HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(e);

            StreamReader data = new StreamReader(response.GetResponseStream());

            string line;
            List<Area> areas = new List<Area>();
            while ((line = data.ReadLine()) != null)
            {
                string[] parts = line.Split(new char[] { ';' });
                areas.Add(new Area() { Id = Convert.ToInt32(parts[0]), Name = parts[1], Polygon = parts[2] });
            }

            Dispatcher.BeginInvoke(() => { cboAreas.ItemsSource = areas; });
        }
    }
}
