package it.enea.cruise.repositories;

import java.util.List;
import java.util.Optional;


import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.transaction.annotation.Transactional;

import it.enea.cruise.model.user.Device;
import it.enea.cruise.model.user.User;

public interface UserRepository extends JpaRepository<User, Long>{
	
	Optional<User> findByUserid(Long userid);
	
	@Transactional(noRollbackFor=Exception.class)
	User findBySubject(String subject);
	
	@Query ("SELECT u FROM user as u JOIN userCommunity as uc ON u.userid = uc.id.userid WHERE uc.id.communityid = ?1")
	List<User> findAllByCommunityId(Long communityid);

	@Query("Select d from device d WHERE d.user.userid = :userid")
	List<Device> findAllDevicesByUserid(@Param("userid") Long userid);
	
	@Query("Select u from user as u WHERE u.subject LIKE :subject")
	User findUserBySubject(@Param("subject") String subject);
		
	List<User> findBySubjectIsNotNull();
	
	@Query ("SELECT u FROM user as u JOIN userCommunity as uc ON u.userid = uc.id.userid WHERE u.subject IS NOT NULL AND uc.id.communityid = ?1")
	List<User> findBySubjectIsNotNullAndCommunityId(Long communityid);
	
	@Query ("SELECT u FROM user as u JOIN userCommunity as uc ON u.userid = uc.id.userid WHERE u.subject IS NOT NULL AND uc.active = TRUE AND uc.id.communityid = ?1")
	List<User> findBySubjectIsNotNullAndActiveIsTrueAndCommunityId(Long communityid);

	
	@Query ("SELECT count(*) FROM user as u JOIN userCommunity as uc ON u.userid = uc.id.userid WHERE u.subject IS NOT NULL AND uc.id.communityid = ?1")
	Integer countBySubjectIsNotNullAndCommunityId(Long communityid);
	
	@Query ("SELECT u FROM user as u JOIN userCommunity as uc ON u.userid = uc.id.userid WHERE uc.wallet = ?1")
	List<User> findFromWallet(String wallet);
	
	@Query ("SELECT u FROM user as u JOIN userCommunity as uc ON u.userid = uc.id.userid WHERE uc.wallet = ?1 AND uc.id.communityid = ?2")
	List<User> findFromWalletAndCommunityId(String wallet, Long communityid);
	
}
