using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Domain;
using Dao;

namespace Service.Implement
{
	public class SysRoleManager : GenericManagerBase<SysRole>, ISysRoleManager
	{
		public ISysUserRepository SysUserRepository { get; set; }

		public ISysAuthorityRepository SysAuthorityRepository { get; set; }

		public IList<SysRole> LoadAllByPage(out long total, int page, int rows, string order, string sort)
		{
			return ((Dao.ISysRoleRepository)(this.CurrentRepository)).LoadAllByPage(out total, page, rows, order, sort).ToList();
		}

		public SysRole Get(string name)
		{
			return ((Dao.ISysRoleRepository)(this.CurrentRepository)).Get(name);
		}

		public override void Delete(IList<object> idList)
		{
			if (idList != null) {
				foreach (int roleId in idList.Cast<int>()) {
					if (!Deletable(roleId)) {
						throw new Exception("角色已分配给用户不能删除。");
					}
				}
			}

			base.Delete(idList);
		}

		public override void Delete(object id)
		{
			if (!Deletable((int)id)) {
				throw new ApplicationException("角色已分配给用户不能删除。");
			}

			base.Delete(id);
		}

		/// <summary>
		/// 判断角色是否可以删除。
		/// 如果一个角色已分配给用户，则此角色不可以被删除
		/// </summary>
		/// <param name="roleId"></param>
		/// <returns></returns>
		public bool Deletable(int roleId) 
		{
			IList<SysUsers> users = SysUserRepository.GetByRole(roleId);
			if (users == null || users.Count == 0) {
				return true;
			}

			return false;
		}

		public void SaveRoleAuthorities(int roleId, IList<int> authorityIdList)
		{
			SysRole role = CurrentRepository.Get(roleId);

			if (role.Name == "超级管理员") {
				throw new ApplicationException("不能修改超级管理员的权限！");	
			}

			role.Authorities.Clear();

			if (authorityIdList != null && authorityIdList.Count > 0)
			{
				foreach (int authorityId in authorityIdList) 
				{
					role.Authorities.Add(SysAuthorityRepository.Get(authorityId));
				}
			}

			this.Update(role);
		}


        public IList<SysAuthority> GetAuthorities(SysRole role)
        {
            IList<SysAuthority> list = new List<SysAuthority>();

            var roleEntity = ((Dao.ISysRoleRepository)(this.CurrentRepository)).LoadAll().FirstOrDefault(r => r == role);

            if (roleEntity != null)
            {
                list = roleEntity.Authorities;
            }
            return list;
        }
    }
}
