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

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.TopicCarouselDao;
import com.apobates.forum.core.entity.TopicCarousel;

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

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

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public Optional<Boolean> edit(TopicCarousel updateEntity) {
		try {
			entityManager.merge(updateEntity);
			return Optional.of(true);
		}catch(Exception e) {
			if(logger.isDebugEnabled()){
				logger.debug(e.getMessage(), e);
			}
		}
		return Optional.empty();
	}

	@Override
	public Stream<TopicCarousel> findAll() {
		return entityManager.createQuery("SELECT tc FROM TopicCarousel tc", TopicCarousel.class).getResultStream();
	}

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

	@Override
	public Optional<TopicCarousel> findOne(String title) {
		TopicCarousel tc = null;
		
		try{
			tc = entityManager.createQuery("SELECT tc FROM TopicCarousel tc WHERE tc.title = ?1 AND tc.status = ?2", TopicCarousel.class)
					.setParameter(1, title)
					.setParameter(2, true)
					.getSingleResult();
		}catch(javax.persistence.NoResultException e){
			if(logger.isDebugEnabled()){
				logger.debug(e.getMessage(), e);
			}
		}
		return Optional.ofNullable(tc);
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public Optional<Boolean> editStatus(int id, boolean status) {
		int affect = entityManager.createQuery("UPDATE TopicCarousel tc SET tc.status = ?1 WHERE tc.id = ?2")
				.setParameter(1, status)
				.setParameter(2, id)
				.executeUpdate();
		return affect == 1 ? Optional.of(true) : Optional.empty();
	}
}
