using Valg.EVA.Skanning.UserInterfaceElements.Commands;
using Valg.EVA.Skanning.Identity;
using System.Collections.ObjectModel;
using System.Linq;
using Valg.EVA.Skanning.Contracts.Security;
using Valg.EVA.Skanning.UserInterfaceElements.ApplicationEvents;

namespace Valg.EVA.Skanning.UserInterfaceElements.RoleSelector
{
    public class RoleSelectorViewModel : ViewModelBase, IRoleSelectorViewModel
    {
        private readonly IIdentityProvider identityProvider;

        public RoleSelectorViewModel(IIdentityProvider identityProvider)
        {
            this.identityProvider = identityProvider;
            SelectRoleCommand = new RelayCommand(RoleSelected);
        }

        public RelayCommand SelectRoleCommand { get; set; }

        public ObservableCollection<RoleViewModel> Roles
        {
            get
            {
                var roles = new ObservableCollection<RoleViewModel>();
                foreach (var role in identityProvider.Roles
                    .Where(p => p.IsSubArea == false && !string.IsNullOrEmpty(p.ElectionName) && !string.IsNullOrEmpty(p.ContestName))
                    .OrderBy(r => r.ElectionName)
                    .ThenBy(r => r.Area.AreaName))
                {
                    roles.Add(new RoleViewModel(role, identityProvider));
                }
                return roles;
            }
        }

        public string ElectionEventName
        {
            get { return identityProvider.ClaimValue(ClaimDefinitions.ElectionEventNameClaimType); }
        }

        private void RoleSelected(object obj)
        {
            var viewModel = obj as ISelectedRoleViewModel;
            identityProvider.SetCurrentRole(viewModel.Role);

            PublishEvent<MainWindowRequestedEvent, System.EventArgs>(System.EventArgs.Empty);
        }
    }
}
