using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations.Schema;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace Entities.Contracts
{
	[Table("submissions")]
	public class Submission
	{
		[Key]
		[Column("id")]
		public Guid Id { get; set; }

		[Required]
		[Column("exam_id")]
		public Guid ExamId { get; set; }
		[ForeignKey(nameof(ExamId))]
		public virtual Exam Exam { get; set; }

		[Required]
		[Column("student_id")]
		public Guid StudentId { get; set; }
		[ForeignKey(nameof(StudentId))]
		public virtual User Student { get; set; }

		[Column("graded_by")]
		public Guid? GraderId { get; set; }
		[ForeignKey(nameof(GraderId))]
		public virtual User Grader { get; set; }

		[Column("class_id")]
		public Guid ClassId { get; set; }
		[ForeignKey(nameof(ClassId))]
		public virtual Class Class { get; set; }

		[Required]
		[Column("attempt_number")]
		public byte AttemptNumber { get; set; }  // 第几次提交

		[Column("submission_time")]
		public DateTime SubmissionTime { get; set; }

		[Column("overall_grade")]
		public float OverallGrade { get; set; } = 0;

		[Column("overall_feedback")]
		public string? OverallFeedback { get; set; }

		[Column("graded_at")]
		public DateTime? GradedAt { get; set; }

		[Required]
		[Column("status")]
		public SubmissionStatus Status { get; set; }

		[Column("deleted")]
		public bool IsDeleted { get; set; }
		// Navigation Properties

		[NotMapped]
		public int ErrorCount => SubmissionDetails.Where(sd => sd?.IsCorrect == false && sd.IsCorrect != null).Count();

		[NotMapped]
		public Dictionary<string, int> ErrorQuestionTypeDistribution => SubmissionDetails
			.Where(sd => sd?.IsCorrect == false)
			.GroupBy(sd => sd.ExamQuestion.Type.Name)
			.ToDictionary(g => g.Key, g => g.Count());

		[NotMapped]
		public Dictionary<string, int> ErrorQuestionLessonDistribution => SubmissionDetails
			.Where(sd => sd?.IsCorrect == false && sd.ExamQuestion.Question?.Lesson != null)
			.GroupBy(sd => sd.ExamQuestion.Question.Lesson.Title)
			.ToDictionary(g => g.Key, g => g.Count());



		[InverseProperty(nameof(SubmissionDetail.Submission))]
		public virtual ICollection<SubmissionDetail> SubmissionDetails { get; set; }

		public Submission()
		{
			Id = Guid.NewGuid();
			SubmissionDetails = new HashSet<SubmissionDetail>();
		}
	}

}
