using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Newtonsoft.Json; using StudyLib.API.Data; using StudyLib.Models; namespace StudyLib.API.Controllers { [Route("api/[controller]")] [Authorize] [ApiController] public class SubjectsController : ControllerBase { private readonly StudyLibContext _context; public SubjectsController(StudyLibContext context) { _context = context; } [HttpGet("list-by-group-id/{groupId}")] public async Task>> GetSubjects(long groupId) { return await _context.Subjects.Where(s => s.Group.ID == groupId).Include(s => s.Comments).Include(s => s.Assignments).Include(s => s.Tests).ToListAsync(); } [HttpGet("get-by-id/{id}/{userId}")] public async Task> GetSubject(long id, string userId) { var subject = await _context.Subjects.Where(s => s.ID == id).Include(s => s.Comments).Include(s => s.Assignments).Include(s => s.Tests).SingleOrDefaultAsync(); if (subject == null) { return NotFound(); } subject.EditedBy = userId; _context.Entry(subject).State = EntityState.Modified; await _context.SaveChangesAsync(); return subject; } [HttpPut("update/{id}")] public async Task PutSubject(long id, Subject subject) { if (id != subject.ID) { return BadRequest(); } _context.Entry(subject).State = EntityState.Modified; foreach (var comment in subject.Comments) { if (comment.ID >= 1) { _context.Entry(comment).State = EntityState.Modified; } else { _context.Comments.Add(comment); } } foreach (var assignment in subject.Assignments) { if (assignment.ID >= 1) { _context.Entry(assignment).State = EntityState.Modified; } else { _context.Assignments.Add(assignment); } } foreach (var test in subject.Tests) { if (test.ID >= 1) { _context.Entry(test).State = EntityState.Modified; } else { _context.Tests.Add(test); } } try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SubjectExists(id)) { return NotFound(); } else { throw; } } return NoContent(); } [HttpPost("add")] public async Task> PostSubject(Subject subject) { _context.Subjects.Add(subject); await _context.SaveChangesAsync(); return CreatedAtAction("GetSubject", new { id = subject.ID }, subject); } // DELETE: api/Subjects/5 [HttpDelete("delete/{id}")] public async Task> DeleteSubject(long id) { var subject = await _context.Subjects.FindAsync(id); if (subject == null) { return NotFound(); } _context.Subjects.Remove(subject); await _context.SaveChangesAsync(); return subject; } [HttpGet("unlock/{id}")] public async Task> UnlockSubject(long id) { var subject = await _context.Subjects.FindAsync(id); if (subject == null) { return NotFound(); } subject.EditedBy = null; _context.Entry(subject).State = EntityState.Modified; await _context.SaveChangesAsync(); return NoContent(); } private bool SubjectExists(long id) { return _context.Subjects.Any(e => e.ID == id); } } }