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

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

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

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

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