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

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

	@Override
	public Optional<TopicConfig> findOne(Long primaryKey) {
		return Optional.ofNullable(entityManager.find(TopicConfig.class, primaryKey));
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public Optional<Boolean> edit(TopicConfig 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<TopicConfig> findAll() {
		return Stream.empty();
	}

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

	@Override
	public Optional<TopicConfig> findOneByTopic(long topicId) {
		try {
			TopicConfig tc = entityManager.createQuery("SELECT tc FROM TopicConfig tc WHERE tc.topicId = ?1", TopicConfig.class).setParameter(1, topicId).getSingleResult();
			return Optional.ofNullable(tc);
		}catch(javax.persistence.NoResultException e) {
			if(logger.isDebugEnabled()){
				logger.debug(e.getMessage(), e);
			}
		}
		return Optional.empty();
	}

}
