using Valg.EVA.Skanning.ServicesModel.ElectionConfig.DataProvider;
using Valg.EVA.Skanning.ServicesModel.ElectionConfig.Model;
using System.Collections.ObjectModel;
using System.Linq;
using Prism.Commands;

namespace Valg.EVA.Skanning.UserInterfaceElements.EmergencyMode
{
    public class SelectCountyViewModel : ViewModelBase, IConfigureEmergencyModeDetailModel
    {
        private readonly IMunicipalityDataProvider municipalityDataProvider;
        private County currentSelectedCounty;

        public SelectCountyViewModel(IMunicipalityDataProvider municipalityDataProvider)
        {
            this.municipalityDataProvider = municipalityDataProvider;            
            Counties = new ObservableCollection<County>();

            RadioButtonSelectedCommand = new DelegateCommand<County>(RadioButtonSelected);
        }

        public bool IsNextButtonVisible => true;
        public DelegateCommand<County> RadioButtonSelectedCommand { get; private set; }

        public ElectionEvent CurrentElectionEvent { get; private set; }

        public bool IsNextButtonEnabled => CurrentSelectedCounty != null;

        public string Title => Resources.Language.LanguageString.EmergencyMode_SelectCountyView_Title;

        public ObservableCollection<County> Counties { get; }

        public string NextButtonText => Resources.Language.LanguageString.Button_Next;

        public County CurrentSelectedCounty
        {
            get { return currentSelectedCounty; }
            set
            {
                currentSelectedCounty = value;
                OnPropertyChanged(nameof(IsNextButtonEnabled));
            }
        }

        internal void UpdateCountyList()
        {
            if (CurrentElectionEvent != null)
            {
                var counties = municipalityDataProvider.GetAllCounties(CurrentElectionEvent.Id);
                Counties.Clear();
                Counties.AddRange(counties.OrderBy(p => p.Name));
            }
        }

        private void RadioButtonSelected(County selectedCounty)
        {
            CurrentSelectedCounty = selectedCounty;
        }

        internal void SetCurrentElectionEvent(ElectionEvent electionEvent)
        {
            CurrentElectionEvent = electionEvent;
        }
    }
}
