package org.ros.chatto.repository;

import java.util.List;

import org.ros.chatto.model.ChatMessage;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Repository;
import java.time.Instant;

@Repository
public interface ChatMessageRepository
		extends JpaRepository<ChatMessage, Long> {
	@Query("select m from ChatMessage  m join fetch m.messageCipher mc join fetch m.toUser tu join fetch m.fromUser fu "
			+ "where (tu.userName = ?1 or tu.userName = ?2) and "
			+ "(fu.userName = ?1 or fu.userName = ?2) order by m.messageTime asc")
	public List<ChatMessage> getAllMessages(String fromUser, String toUser);

	@Query("select m from ChatMessage  m join fetch m.messageCipher mc join fetch m.toUser tu join fetch m.fromUser fu "
			+ "where (tu.userName = ?1 or tu.userName = ?2) and "
			+ "(fu.userName = ?1 or fu.userName = ?2) and (m.messageTime > ?3) order by m.messageTime asc")
	public List<ChatMessage> getNewMessages(String fromUser, String toUser,
			Instant lastMessageTime);

	@Query("select m from ChatMessage  m join fetch m.messageCipher mc join fetch m.toUser tu join fetch m.fromUser fu "
			+ "where (tu.userName = ?1 or tu.userName = ?2) and "
			+ "(fu.userName = ?1 or fu.userName = ?2) order by m.messageTime desc")
	public List<ChatMessage> getAllMessages(String fromUser, String toUser,
			PageRequest pageRequest);

	@Query("select count(c) from ChatMessage c")
	public Long totalMessages();

	@Query("select count(c) from ChatMessage c where c.messageTime=?1")
	public Long messagesOnDate(Instant date);
}