using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using System.Collections.Generic;

namespace EsriMapSamples.ViewModel
{
    public class MainViewModel : BaseViewModel
    {
        #region Fields

        private RelayCommand _saveCommand;
        private RelayCommand _saveXMLCommand;
        private RelayCommand _loadXMLCommand;
        private RelayCommand _addUserCommand;
        private ObservableCollection<User> _users;

        #endregion

        #region Constructor

        public MainViewModel()
        {
            if (!App.IsDesignTime)
            {
                _users = new ObservableCollection<User>();
                LoadUsers();
            }
        }

        #endregion

        public ObservableCollection<User> Users
        {
            get 
            {
                return _users; 
            }
        }

        public void LoadUsers()
        {
            _users.Add(new User() { FirstName = "George", LastName = "Lewis", Latitude = 40, Longitude = -80 });
        }

        public void AddUser(User u)
        {
            _users.Add(u);
        }

        public User GetClosestUser(Point p)
        {
            double x1 = p.X;
            double y1 = p.Y;
            User prevUser;
            if (_users.Count > 0)
            {
                prevUser = _users[0];
            }
            else
            {
                prevUser = null;
            }
            double prevValue = double.MaxValue;
            foreach (User user in _users)
            {
                double distance = Math.Sqrt(Math.Pow(user.Longitude - x1, 2) + Math.Pow(user.Latitude - y1, 2));
                if (distance < prevValue)
                {
                    prevValue = distance;
                    prevUser = user;
                }
            }
            return prevUser;
        }

        #region Commanding

        public ICommand AddUserCommand
        {
            get
            {
                if (_addUserCommand == null)
                {
                    _addUserCommand = new RelayCommand(p => true, p => this.AddUser((User)p));
                }
                return _addUserCommand;
            }
        }
        #endregion
    }

    public class User
    {
        public User()
        {
            //empty
        }

        public User(double lon, double lat)
        {
            this.Latitude = lat;
            this.Longitude = lon;
        }

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public double Longitude { get; set; }
        public double Latitude { get; set; }
    }
}
