using System.Collections.Generic;
using SilverlightSqlSpatial.Map.SilverlightSqlSpatial.Services;
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data.Services.Client;
using System.Linq;

namespace SilverlightSqlSpatial.Map.ViewModels
{
    public class MapViewModel : INotifyPropertyChanged
    {
        private SilverlightSqlSpatial.Services.DataManager dataContext;
        private DataServiceQuery<County> query;
        private ObservableCollection<County> spatialData;

        /// <summary>
        /// Initializes a new instance of the <see cref="MapViewModel" /> class.
        /// </summary>
        public MapViewModel()
        {
            dataContext = new SilverlightSqlSpatial.Services.DataManager(new Uri("http://localhost:5953/MapService.svc/"));

            query = dataContext.CreateQuery<County>("Counties");
            query.BeginExecute(new AsyncCallback(OnSpatialLoaded), null);
        }
        /// <summary>
        /// Occurs when a property value changes.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        public ObservableCollection<County> SpatialData
        {
            get
            {
                return spatialData;
            }
            set
            {
                spatialData = value;
                OnPropertyChanged("SpatialData");
            }
        }

        protected virtual void OnPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        /// <summary>
        /// Called when {6CBDD833-7AC5-4ED2-BC4D-FC83C448DFEC}[spatial loaded].
        /// </summary>
        /// <param name="ar">The ar.</param>
        private void OnSpatialLoaded(IAsyncResult ar)
        {
            IEnumerable<County> spatialResult = query.EndExecute(ar);
            SpatialData = new ObservableCollection<County>(spatialResult);
        }
    }
}