using System;
using System.ComponentModel;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml.Data;
using System.Data.Services.Client;
using Filter.NorthwindServiceReference;
using C1.Xaml;

namespace Filter
{
    class ViewModel : BaseObject
    {
        // ** fields
        C1CollectionView _invoices;
        bool _finishedLoading;

        // ** ctor
        public ViewModel()
        {
            // create invoice list
            var invoices = new DataServiceCollection<Invoice>();

            // create invoice view
            _invoices = new C1CollectionView(invoices);

            // load the invoices asynchronously
            var ctx = new NorthwindEntities(new Uri("http://services.odata.org/Northwind/Northwind.svc/"));
            invoices.LoadCompleted += (s, e) =>
            {
                if (invoices.Continuation != null)
                {
                    invoices.LoadNextPartialSetAsync();
                }
                else
                {
                    FinishedLoading = true;
                }
            };
            FinishedLoading = false;
            invoices.LoadAsync(ctx.Invoices);
        }

        // ** object model
        public bool FinishedLoading
        {
            get { return _finishedLoading; }
            set { SetValue(ref _finishedLoading, value, "FinishedLoading"); }
        }
        public ICollectionView Invoices
        {
            get { return _invoices; }
        }
    }

    /// <summary>
    /// Object that implements INotifyPropertyChanged.
    /// </summary>
    public class BaseObject : INotifyPropertyChanged
    {
        // ** INotifyPropertyChanged
        public event PropertyChangedEventHandler PropertyChanged;
        protected virtual void OnPropertyChanged(string propName)
        {
            if (PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs(propName));
        }
        protected bool SetValue<T>(ref T field, T value, string propertyName)
        {
            if (!EqualityComparer<T>.Default.Equals(field, value))
            {
                field = value;
                OnPropertyChanged(propertyName);
                return true;
            }
            return false;
        }
    }
}
