package es.uv.saic.domain;

import java.util.List;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;

@Repository
public interface AcreditacioRepository extends JpaRepository<Acreditacio, AcreditacioPK> {

	@Query(value="SELECT ac.* FROM acreditacions ac "
			+ "	LEFT JOIN organs og ON ac.tlugar = og.tlugar AND ac.lugar = og.lugar "
			+ " WHERE og.actiu "
			+ "	ORDER BY grup_curs DESC, grup_num ASC; ", nativeQuery=true)
	List<Acreditacio> getAll(); 
	
	@Query(value="SELECT * FROM acreditacions "
			+ "	  WHERE grup_curs = date_part('year', CURRENT_DATE) AND grup_num >= date_part('month', CURRENT_DATE) "
			+ "   ORDER BY grup_num", nativeQuery=true)
	List<Acreditacio> getNextsCurrentYear(); 
	
	@Query(value="SELECT * FROM acreditacions  WHERE grup_curs = ?1 AND grup_num = ?2  ORDER BY grup_num", nativeQuery=true)
	List<Acreditacio> getByCursGrup(Integer curs, Integer grup); 
	
	@Query(value="SELECT ac.* FROM acreditacions ac "
			+ "   LEFT JOIN organs og ON ac.lugar = og.lugar AND ac.tlugar = og.tlugar"
			+ "	  WHERE ac.grup_curs = ?1 AND ac.grup_num = ?2 AND og.tambit = ?3 ORDER BY grup_num", nativeQuery=true)
	List<Acreditacio> getByCursGrupTambit(Integer curs, Integer grup, String tambit); 
	
	@Query(value="SELECT * FROM acreditacions  WHERE grup_curs = ?1  ORDER BY grup_num", nativeQuery=true)
	List<Acreditacio> getByCurs(Integer curs); 
	
	@Query(value="SELECT * FROM acreditacions "
			+ "   WHERE tlugar = ?1 AND lugar = ?2 "
			+ "	  ORDER BY data_acred DESC LIMIT 1;", nativeQuery=true)
	Acreditacio getByOrgan(String tlugar, Integer lugar);
	
	@Query(value="SELECT * FROM acreditacions "
			+ "   WHERE (tlugar, lugar) IN(SELECT tlugar, lugar FROM organs WHERE tlugar2 = ?1 AND lugar2 = ?2)"
			+ "	  ORDER BY grup_curs, grup_num", nativeQuery=true)
	List<Acreditacio> getByCentre(String tlugar, Integer lugar);
	
}
