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.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.apobates.forum.core.api.dao.AlbumPictureDao;
import com.apobates.forum.core.entity.AlbumPicture;


@Repository
public class AlbumPictureDaolmpl implements AlbumPictureDao{
	@PersistenceContext
	private EntityManager entityManager;
	private final static Logger logger = LoggerFactory.getLogger(AlbumPictureDaolmpl.class);
	
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void save(AlbumPicture entity) {
		entityManager.persist(entity);
	}

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

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

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

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

	@Override
	public Stream<AlbumPicture> findAllByAlbum(long albumId) {
		return entityManager.createQuery("SELECT ap FROM AlbumPicture ap WHERE ap.status = ?1 AND ap.album.id = ?2", AlbumPicture.class).setParameter(1, true).setParameter(2, albumId).getResultStream();
	}
	
	@Override
	public Stream<AlbumPicture> findAllByAlbum(Collection<Long> albumIdSet) {
		if(albumIdSet == null || albumIdSet.isEmpty()){
			return Stream.empty();
		}
		return entityManager.createQuery("SELECT ap FROM AlbumPicture ap WHERE ap.status = ?1 AND ap.album.id IN ?2", AlbumPicture.class).setParameter(1, true).setParameter(2, albumIdSet).getResultStream();
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public int delete(Collection<Long> idSet) {
		if(idSet == null || idSet.isEmpty()){
			return -1;
		}
		int affect = entityManager.createQuery("UPDATE AlbumPicture ap SET ap.status = ?1 WHERE ap.id IN ?2").setParameter(1, false).setParameter(2, idSet).executeUpdate();
		return affect;
	}
	
}
