using Entities.Contracts;
using Entities.DTO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Net;
using System.Security.Claims;
using TechHelper.Services;

namespace TechHelper.Server.Controllers
{
	[Route("api/class")]
	[ApiController]
	public class ClassController : ControllerBase
	{
		private IClassService _classService;
		private UserManager<User> _userManager;
		public ClassController(IClassService classService, UserManager<User> userManager)
		{
			_classService = classService;
			_userManager = userManager;
		}

		[HttpPost("userRegiste")]
		public async Task<IActionResult> UserRegisterToClass(
			[FromBody] UserRegistrationToClassDto toClass)
		{

			var result = await _classService.UserRegister(toClass);

			if (!result.Status) return BadRequest(result.Message);

			return Ok();
		}




		[HttpPost("getClassStudents")]
		public async Task<IActionResult> GetClassStudents()
		{
			if (User.IsInRole("Teacher"))
			{
				var gradeClaim = User.FindFirst("Grade")?.Value;
				var classClaim = User.FindFirst("Class")?.Value;

				if (string.IsNullOrEmpty(gradeClaim) || string.IsNullOrEmpty(classClaim))
				{
					return BadRequest("未识别到你加入的班级信息（年级或班级声明缺失）。");
				}

				if (!byte.TryParse(gradeClaim, out byte grade) || !byte.TryParse(classClaim, out byte cla))
				{
					return BadRequest("你班级或年级信息格式不正确。");
				}

				var classDto = new ClassDto
				{
					Grade = grade,
					Class = cla
				};

				var result = await _classService.GetClassStudents(classDto);
				var css = result.Result as ICollection<ClassStudent>;
				if (css == null) return BadRequest("你还没有学生");


				List<StudentDto> sts = new List<StudentDto>();
				css?.ToList().ForEach(s => sts.Add(new StudentDto
				{
					DisplayName = s.Student.DisplayName,
					Id = s.Student.Id,
				}));

				if (!result.Status)
				{
					return BadRequest(result.Message);
				}
				return Ok(sts);
			}
			else
			{
				return BadRequest("你没有权限查看，未识别到你的教师身份。");
			}
		}

		[HttpPost("Create")]
		public async Task<IActionResult> Create(
			[FromBody] ClassDto classDto)
		{
			var result = await _classService.AddAsync(classDto);
			if (!result.Status) return BadRequest(result.Message);

			return Ok();
		}

		[HttpPost("GetGradeClasses")]
		public async Task<IActionResult> GetGradeClasses(
		[FromBody] byte classDto)
		{
			var result = await _classService.GetGradeClasses(classDto);
			if (!result.Status) return BadRequest(result.Message);

			return Ok(result.Result);
		}
	}
}
