Skip to content
Snippets Groups Projects
CourseService.cs 2.18 KiB
Newer Older
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Tsi1.BusinessLayer.Dtos;
using Tsi1.BusinessLayer.Helpers;
using Tsi1.BusinessLayer.Interfaces;
using Tsi1.DataLayer;
using Tsi1.DataLayer.Entities;

namespace Tsi1.BusinessLayer.Services
{
    public class CourseService : ICourseService
    {
        private readonly Tsi1Context _context;

        public CourseService(Tsi1Context context)
        {
            _context = context;
        }

        public async Task<ServiceResult<Course>> Create(CourseCreateDto newCourse)
        {
            var result = new ServiceResult<Course>();

            var course = new Course()
            {
                Name = newCourse.Name
            };

            _context.Courses.Add(course);
            await _context.SaveChangesAsync();

            result.Data = course;
            return result;
        }

esantangelo's avatar
esantangelo committed
        public async Task<ServiceResult<List<CoursePreviewDto>>> GetCoursePreviews(string userType, int tenantId)
        {
            var result = new ServiceResult<List<CoursePreviewDto>>();
            result.Data = new List<CoursePreviewDto>();

            var courses = new List<Course>();

            if (userType == UserTypes.Student)
            {
                courses = await _context.StudentCourses
                    .Include(x => x.Course)
esantangelo's avatar
esantangelo committed
                    .Where(x => x.Course.TenantId == tenantId)
                    .Select(x => x.Course)
                    .ToListAsync();
            }
            else if (userType == UserTypes.Professor)
            {
                courses = await _context.ProfessorCourses
                    .Include(x => x.Course)
esantangelo's avatar
esantangelo committed
                    .Where(x => x.Course.TenantId == tenantId)
                    .Select(x => x.Course)
                    .ToListAsync();
            }

            foreach (var course in courses)
            {
                var item = new CoursePreviewDto()
                {
                    Id = course.Id,
                    Name = course.Name
                };

                result.Data.Add(item);
            }

            return result;
        }
    }
}