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 : IProjectService
    {

        [PrincipalPermission(SecurityAction.Demand, Role = "VIEW_PROJECTS")]
        public async Task<IEnumerable<ProjectDto>> GetProjectsAsync(FilterDto filterDto)
        {
            var retval = new List<ProjectDto>();
            using (var projectUnit = new UnitOfWork<Project>(new ISDbContext()))
            {
                var filter = _mapper.Map<Filter>(filterDto);
                var projects = await projectUnit.GetAsync(filter);

                foreach(var project in projects)
                {
                    retval.Add(_mapper.Map<ProjectDto>(project));
                }
            }

            return retval;
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "VIEW_PROJECTS")]
        public async Task<ProjectDto> GetProjectByIdAsync(int id)
        {
            ProjectDto retval;
            using (var projectUnit = new UnitOfWork<Project>(new ISDbContext()))
            {
                var project = await projectUnit.GetByIdAsync(id);

                retval = _mapper.Map<ProjectDto>(project);
            }

            return retval;
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "EDIT_PROJECTS")]
        public async Task CreateProjectAsync(ProjectDto projectDto)
        {
            using (var projectUnit = new UnitOfWork<Project>(new ISDbContext()))
            {
                var project = _mapper.Map<Project>(projectDto);
                project.ResponsibleEmployee = null;
                await projectUnit.CreateAsync(project);
            }
        }

        [PrincipalPermission(SecurityAction.Demand, Role = "EDIT_PROJECTS")]
        public async Task UpdateProjectAsync(ProjectDto projectDto)
        {
            using (var projectUnit = new UnitOfWork<Project>(new ISDbContext()))
            {
                var project = _mapper.Map<Project>(projectDto);
                await projectUnit.UpdateAsync(project);
            }
        }

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

    }
}
