using C1.Xaml;
using SearchContract.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.UI.Xaml;

namespace SearchContract
{
    public class SearchViewModel : INotifyPropertyChanged
    {
        private C1CollectionView _customersView;
        private static SearchViewModel _instance;
        private string _query;

        public static SearchViewModel Instance
        {
            get
            {
                if (_instance == null)
                {
                    _instance = new SearchViewModel();
                }
                return _instance;
            }
        }

        private SearchViewModel()
        {
            var customers = CustomerDataSource.GetCustomers();
            _customersView = new C1CollectionView();
            _customersView.SourceCollection = customers;
        }

        public C1CollectionView CollectionView
        {
            get
            {
                return _customersView;
            }
        }

        public string Query
        {
            get
            {
                return _query;
            }
        }

        public Visibility QueryVisibility
        {
            get
            {
                return string.IsNullOrWhiteSpace(_query) ? Visibility.Collapsed : Visibility.Visible;
            }
        }

        public void Filter(string query)
        {
            // set filter based on search query
            _query = query.ToLower();
            _customersView.Filter = null;
            if (!string.IsNullOrWhiteSpace(query))
            {
                _customersView.Filter = null;
                _customersView.Filter = delegate(object item)
                {
                    Customer c = item as Customer;
                    if (c != null)
                    {
                        if (c.Country.ToLower().Contains(_query) ||
                            c.Name.ToLower().Contains(_query))
                            return true;
                    }
                    return false;
                };
            }
            OnPropertyChanged("Query");
            OnPropertyChanged("QueryVisibility");
        }

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