using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Security;
using Qusion.WebApp.Areas.Qusion.Models.Roles;

namespace Qusion.WebApp.Areas.Qusion.Controllers.Api
{
    public class RolesController : ApiController
    {
        /// <summary>
        /// Return list of roles.
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage Index()
        {
            IList<RoleListItem> roles = Roles.GetAllRoles().Select(role => new RoleListItem
                                                                               {
                                                                                   Role = role, Users = Roles.GetUsersInRole(role).Length
                                                                               }).ToList();
            return Request.CreateResponse(HttpStatusCode.OK, roles);
        }

        /// <summary>
        /// Create new role.
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage Create(RoleInputModel input)
        {
            if (!string.IsNullOrEmpty(input.Role) && !Roles.RoleExists(input.Role))
            {
                Roles.CreateRole(input.Role);
                 return Request.CreateResponse(HttpStatusCode.OK);
            }
            return Request.CreateResponse(HttpStatusCode.OK, new {Error = true});
        }

        /// <summary>
        /// Delete existing role.
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage Delete(RoleInputModel input)
        {
            if (!string.IsNullOrEmpty(input.Role) && Roles.RoleExists(input.Role) && Roles.GetUsersInRole(input.Role).Length == 0)
            {
                if (input.Role == "Administrator" || input.Role == "Guest")
                    return Request.CreateResponse(HttpStatusCode.OK,
                                                  new {Error = true, Message = "You can't delete the system roll."});
                Roles.DeleteRole(input.Role);
                return Request.CreateResponse(HttpStatusCode.OK);
            }
            return Request.CreateResponse(HttpStatusCode.OK, new { Error = true, Message = "You can't delete the roll that has users." });
        }
    }
}