using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using GalaSoft.MvvmLight;

namespace MvvmLightDemo.ViewModel
{
    /// <summary>
    /// This class contains properties that the main View can data bind to.
    /// <para>
    /// Use the <strong>mvvminpc</strong> snippet to add bindable properties to this ViewModel.
    /// </para>
    /// <para>
    /// You can also use Blend to data bind with the tool's support.
    /// </para>
    /// <para>
    /// See http://www.galasoft.ch/mvvm
    /// </para>
    /// </summary>
    public class MainViewModel : ViewModelBase
    {

        private IDemoDataService _dataService;

        /// <summary>
        /// Initializes a new instance of the MainViewModel class.
        /// </summary>
        public MainViewModel(IDemoDataService dataService)
        {
            _dataService = dataService;
            Customers = new ObservableCollection<Customer>();
            Message = "... Loading ...";

            _dataService.LoadCustomers(CustomersLoaded, CustomerLoadFailed);

        }

        private void CustomersLoaded(IEnumerable<Customer> customers)
        {
            foreach (var customer in customers)
            {
                Customers.Add(customer);
            }
            CurrentCustomer = customers.FirstOrDefault();
            Message = "Customers loaded.";
        }

        private void CustomerLoadFailed(Exception except)
        {
            Message = "Customer Load Failed: " + except.Message;
        }

        public ObservableCollection<Customer> Customers { get; private set; }

        private string _message;
        public string Message
        {
            get { return _message; }
            set { _message = value; RaisePropertyChanged("Message"); }
        }


        private Customer _currentCustomer;
        public Customer CurrentCustomer
        {
            get { return _currentCustomer; }
            set { _currentCustomer = value; RaisePropertyChanged("CurrentCustomer"); }
        }

    }
}