using Valg.EVA.Skanning.UserInterfaceElements;
using Prism.Commands;
using ReactiveUI;
using System.Windows.Input;
using Valg.EVA.Skanning.JobManagement.Startup.Data;

namespace Valg.EVA.Skanning.JobManagement.Startup.UI.PollingDistrict
{
    public class PollingDistrictsViewModel : ReactiveViewModel, IVotingCategoryAwareViewModel
    {
        private readonly IDataModel dataModel;
        
        private bool hasOnlyOnePollingDistrict;

        private IReactiveCollection<PollingDistrictModel> pollingDistricts;
        private bool hasMoreThan1PollingDistrict;

        public PollingDistrictsViewModel(IDataModel dataModel)
        {
            this.dataModel = dataModel;
            RefreshCommand = new DelegateCommand(dataModel.LoadData);
        }

        public IReactiveCollection<PollingDistrictModel> PollingDistricts => pollingDistricts ?? (pollingDistricts = GetPollingDistricts());

        public VotingCategoryType ActiveVotingCategory { get; set; }

        public bool HasOnlyOnePollingDistrict
        {
            get
            {
                return hasOnlyOnePollingDistrict;
            }
            set
            {
                hasOnlyOnePollingDistrict = value;
                OnPropertyChanged();
            }
        }

        public ICommand RefreshCommand { get; set; }

        public bool HasMoreThan1PollingDistrict
        {
            get { return hasMoreThan1PollingDistrict; }
            set
            {
                hasMoreThan1PollingDistrict = value;
                OnPropertyChanged();
            }
        }

        private IReactiveCollection<PollingDistrictModel> GetPollingDistricts()
        {
            var votingCategory = ActiveVotingCategory.Key();
            var districts = dataModel.PollingDistricts.CreateDerivedCollection(
                c => c,
                vm => vm.VotingCategory.Code == votingCategory);

            districts.BubbleCollection(
                d => HasOnlyOnePollingDistrict = d.Count == 1,
                d => HasMoreThan1PollingDistrict = d.Count > 1);

            return districts;
        }
    }
}
