﻿namespace Percepolis.Services
{
    using Data;
    using Data.Entities;
    using Interfaces;
    using System;
    using System.Threading.Tasks;

    public class CourseService : BaseService, ICourseService
    {
        public CourseService(PercepolisDbContext db) : base(db)
        {

        }

        public async Task AddAsync(int institutionId, string title, string shorthand, int? credits)
        {
            var entity = new Course();
            entity.InstitutionId = institutionId;
            entity.Title = title;
            entity.Shorthand = shorthand;
            entity.Credits = credits;
            _db.Courses.Add(entity);
            await _db.SaveChangesAsync();
        }

        public async Task AddTopicAsync(int courseId, int topicId)
        {
            var entity = new CourseTopic();
            entity.CourseId = courseId;
            entity.TopicId = topicId;
            _db.CourseTopics.Add(entity);
            await _db.SaveChangesAsync();
        }

        public async Task<Course> GetByIdAsync(int id)
        {
            var entity = await _db.Courses.FindAsync(id);
            return entity;
        }

        public async Task RemoveByIdAsync(int id)
        {
            var entity = await _db.Courses.FindAsync(id);
            _db.Courses.Remove(entity);
            await _db.SaveChangesAsync();
        }

        public async Task RemoveTopicAsync(int courseId, int topicId)
        {
            var entity = await _db.CourseTopics.FindAsync(courseId, topicId);
            _db.CourseTopics.Remove(entity);
            await _db.SaveChangesAsync();
        }

        public async Task UpdateAsync(int courseId, int institutionId, string title, string shorthand, int? credits)
        {
            var entity = await _db.Courses.FindAsync(courseId);
            entity.InstitutionId = institutionId;
            entity.Title = title;
            entity.Shorthand = shorthand;
            entity.Credits = credits;
            await _db.SaveChangesAsync();
        }
    }
}
