using Valg.EVA.Skanning.Identity;
using System.Collections.ObjectModel;
using System.Linq;

namespace Valg.EVA.Skanning.UserInterfaceElements.RoleSelector
{
    public class RoleViewModel : ViewModelBase, ISelectedRoleViewModel
    {
        private readonly IIdentityProvider identityProvider;
        private bool isChecked;

        public RoleViewModel(Role role, IIdentityProvider identityProvider)
        {
            this.Role = role;
            this.identityProvider = identityProvider;
            this.SubAreaRoles = new ObservableCollection<SubAreaRoleViewModel>();

            if (ShowSubAreas)
            {
                SetSubAreaRoles();
            }
        }

        public Role Role { get; set; }

        public string RoleName
        {
            get
            {
                if (identityProvider.IsInEmergencyMode)
                {
                    return Valg.EVA.Skanning.Resources.Language.LanguageString.EmergencyMode_EmergencyModeDisplayText;
                }
                else
                {
                    return Role.RoleName;
                }
            }
        }

        public string Area
        {
            get { return Role.Area.AreaName; }
        }

        public string Contest
        {
            get { return string.Format("{0} {1} {2}", Role.ElectionName, Valg.EVA.Skanning.Resources.Language.LanguageString.In, Role.ContestName); }
        }

        public bool ShowSubAreas
        {
            get { return Role.Area.Level == Identity.Area.AreaDescription.ElectionLevel.County; }
        }

        public ObservableCollection<SubAreaRoleViewModel> SubAreaRoles { get; private set; }

        public bool IsChecked
        {
            get
            {
                return isChecked;
            }
            set
            {
                isChecked = value;
                OnPropertyChanged();
            }
        }

        private void SetSubAreaRoles()
        {
            var subAreaRoles = identityProvider.Roles.Where(p =>
                p.IsSubArea &&
                p.RoleId == this.Role.RoleId &&
                p.Area.ElectionEventId == this.Role.Area.ElectionEventId &&
                p.Area.CountyId == this.Role.Area.CountyId);

            foreach (var subAreaRole in subAreaRoles.OrderBy(p => p.Area.AreaName))
            {
                this.SubAreaRoles.Add(new SubAreaRoleViewModel(subAreaRole));
            }
        }
    }
}
