using Kimuser.Domain;
using Kimuser.Dto.Items.Roles;
using Kimuser.Dto.Results.Roles;
using Microsoft.AspNetCore.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Kimuser.Services
{
    public interface IRoleService
    {
        List<RoleItem> GetRoles();
        Task<RoleResult> AddRole(string roleName);
    }
    public class RoleService : IRoleService
    {
        private readonly RoleManager<Role> _roleManager;
        public RoleService(RoleManager<Role> roleManager)
        {
            _roleManager = roleManager;
        }

        public List<RoleItem> GetRoles()
        {
            var result = new List<RoleItem>();
            result = _roleManager.Roles.Select(r => new RoleItem()
            {
                Id = r.Id,
                Name = r.Name
            }).ToList();
            return result;
        }

        

        public async Task<RoleResult> AddRole(string roleName)
        {
            var result = new RoleResult();
            var role = new Role() { Name = roleName };
            var identityResult = await _roleManager.CreateAsync(role);
            if (!identityResult.Succeeded)
            {
                result.Result = Dto.Results.Result.Failed;
                result.Message = String.Join("\n", identityResult.Errors.Select(e => e.Description));
            }
            return result;
        }
    }
}
