package com.apobates.forum.core.impl.dao;

import java.util.Collection;
import java.util.Optional;
import java.util.stream.Stream;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.apobates.forum.core.api.dao.PostsDescriptorDao;
import com.apobates.forum.core.entity.PostsDescriptor;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.Pageable;

@Repository
public class PostsDescriptorDaoImpl implements PostsDescriptorDao{
	@PersistenceContext
	private EntityManager entityManager;
	
	@Override
	public Page<PostsDescriptor> findAll(Pageable pageable) {
		return emptyResult();
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void save(PostsDescriptor entity) {
		entityManager.persist(entity);
	}

	@Override
	public Optional<PostsDescriptor> findOne(Long primaryKey) {
		return Optional.ofNullable(entityManager.find(PostsDescriptor.class, primaryKey));
	}

	@Override
	public Optional<Boolean> edit(PostsDescriptor updateEntity) {
		return Optional.empty();
	}

	@Override
	public Stream<PostsDescriptor> findAll() {
		return Stream.empty();
	}

	@Override
	public long count() {
		return -1L;
	}

	@Override
	public Stream<PostsDescriptor> findAllByPosts(Collection<Long> postsIdSet) {
		if(null == postsIdSet || postsIdSet.isEmpty()){
			return Stream.empty();
		}
		return entityManager.createQuery("SELECT pd FROM PostsDescriptor pd WHERE pd.postsId IN ?1", PostsDescriptor.class).setParameter(1, postsIdSet).getResultStream();
	}

}
