using AutoMapper;
using DataAccessLayer;
using DataAccessLayer.Entities;
using DataAccessLayer.Filtering;
using DataAccessLayer.Units;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.Security.Permissions;
using System.ServiceModel;
using System.Text;
using System.Threading.Tasks;
using WcfServices.Contract;
using WcfServices.Dto;
using WcfServices.Mapping;

namespace WcfServices.Services
{
    public partial class ISService : IRoleService
    {

        [PrincipalPermission(SecurityAction.Demand, Role = "BASIC_ACCESS")]
        public async Task<IEnumerable<RoleDto>> GetRolesAsync(FilterDto filterDto)
        {
            var retval = new List<RoleDto>();
            using (var roleUnit = new UnitOfWork<Role>(new ISDbContext()))
            {
                var filter = _mapper.Map<Filter>(filterDto);
                var roles = await roleUnit.GetAsync(filter);

                foreach(var role in roles)
                {
                    retval.Add(_mapper.Map<RoleDto>(role));
                }
            }

            return retval;
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "BASIC_ACCESS")]
        public async Task<RoleDto> GetRoleByIdAsync(int id)
        {
            RoleDto retval;
            using (var roleUnit = new UnitOfWork<Role>(new ISDbContext()))
            {
                var role = await roleUnit.GetByIdAsync(id);

                retval = _mapper.Map<RoleDto>(role);
            }

            return retval;
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "BASIC_ACCESS")]
        public async Task CreateRoleAsync(RoleDto roleDto)
        {
            using (var roleUnit = new UnitOfWork<Role>(new ISDbContext()))
            {
                var role = _mapper.Map<Role>(roleDto);
                await roleUnit.CreateAsync(role);
            }
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "BASIC_ACCESS")]
        public async Task UpdateRoleAsync(RoleDto roleDto)
        {
            using (var roleUnit = new UnitOfWork<Role>(new ISDbContext()))
            {
                var role = _mapper.Map<Role>(roleDto);
                await roleUnit.UpdateAsync(role);
            }
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "BASIC_ACCESS")]
        public async Task DeleteRoleAsync(int id)
        {
            using (var roleUnit = new UnitOfWork<Role>(new ISDbContext()))
            {
                await roleUnit.DeleteAsync(id);
            }
        }

    }
}
