package cn.com.qmth.stmms.biz.mark.dao;

import java.util.List;

import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;

import cn.com.qmth.stmms.biz.mark.model.TrialLibrary;

public interface TrialLibraryDao extends JpaRepository<TrialLibrary, Integer>, JpaSpecificationExecutor<TrialLibrary> {

    List<TrialLibrary> findByExamIdAndSubjectCode(Integer examId, String subjectCode, Pageable page);

    List<TrialLibrary> findByExamIdAndSubjectCodeAndGroupNumber(Integer examId, String subjectCode, Integer groupNumber,
            Pageable page);

    @Query("select l1 from TrialLibrary l1 where l1.examId=?1 and l1.subjectCode=?2 and l1.groupNumber=?3 "
            + "and not exists (select l2.pk.libraryId from TrialHistory l2 where l2.pk.libraryId=l1.id and l2.pk.markerId=?4)")
    List<TrialLibrary> findUnMarked(Integer examId, String subjectCode, Integer groupNumber, Integer markerId,
            Pageable page);

    @Query("select count(l) from TrialLibrary l where l.examId=?1 and l.subjectCode=?2 and l.groupNumber=?3 "
    		 + "and exists (select l2.pk.libraryId from TrialHistory l2 where l2.pk.libraryId=l.id )")
    long countMarked(Integer examId, String subjectCode, Integer groupNumber);

    @Query("select l from TrialLibrary l where l.studentId=?1 order by l.groupNumber ")
    List<TrialLibrary> findByStudentId(Integer studentId);

    List<TrialLibrary> findByStudentIdAndGroupNumber(Integer studentId, Integer groupNumber);

    @Query("select count(*) from TrialLibrary f where f.examId=?1 and f.subjectCode=?2 and f.groupNumber=?3")
    long countByExamIdAndSubjectCodeAndGroupNumber(Integer examId, String subjectCode, Integer groupNumber);

    @Query("select count(*) from TrialLibrary f where f.studentId=?1 and f.groupNumber=?2")
    long countByStudentIdAndGroupNumber(Integer studentId, Integer groupNumber);

    @Modifying
    @Query("delete TrialLibrary m where m.examId=?1 and m.subjectCode=?2 and m.groupNumber=?3")
    void deleteByExamIdAndSubjectCodeAndGroupNumber(Integer examId, String subjectCode, Integer groupNumber);

    @Modifying
    @Query("delete TrialLibrary m where m.studentId=?1")
    void deleteByStudentId(Integer studentId);
    
}
