using System;
using Prism.Commands;
using Valg.EVA.Skanning.UserInterfaceElements;
using Valg.EVA.Skanning.Verify.Startup.StartPage;

namespace Valg.EVA.Skanning.Verify.Startup.Filter
{
    public class FilterViewModel : ViewModelBase
    {
        private string _filterText;

        public FilterViewModel()
        {
            ClearTextFieldCommand = new DelegateCommand(ClearTextField);
        }

        protected override void SubscribeToViewModelSpecificEvents()
        {
            SubscribeToEvent<VerifyStartPageDataWasRefreshedEvent, EventArgs>(DataWasRefreshed);
        }

        private void DataWasRefreshed(EventArgs obj)
        {
            RaiseEvent();
        }

        public string FilterText
        {
            get { return _filterText; }
            set
            {
                _filterText = value;
                RaiseEvent();
                OnPropertyChanged();
                OnPropertyChanged("IsFilterActive");
            }
        }

        public bool IsFilterActive
        {
            get { return !string.IsNullOrWhiteSpace(FilterText) && FilterText.Length > 0; }
        }

        public bool HasOnlyOnePollingDistrict { get; set; }
        
        public DelegateCommand ClearTextFieldCommand { get; private set; }

        private void ClearTextField()
        {
            FilterText = string.Empty;
        }

        private void RaiseEvent()
        {
            if (FilterText != null)
            {
                PublishEvent<FilterChangedEvent, FilterChangedEventArgs>(new FilterChangedEventArgs { Filter = FilterText });
            }
        }
    }
}
