package com.apobates.forum.member.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.member.api.dao.ForumScoreRoleDao;
import com.apobates.forum.member.entity.ForumScoreRole;

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

	@Override
	public Optional<ForumScoreRole> findOne(Integer primaryKey) {
		return Optional.ofNullable(entityManager.find(ForumScoreRole.class, primaryKey));
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public Optional<Boolean> edit(ForumScoreRole 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<ForumScoreRole> findAll() {
		return entityManager.createQuery("SELECT fsr FROM ForumScoreRole fsr", ForumScoreRole.class).getResultStream();
	}

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

	@Override
	public Stream<ForumScoreRole> findAllUsed() {
		return entityManager.createQuery("SELECT fsr FROM ForumScoreRole fsr WHERE fsr.status = ?1", ForumScoreRole.class).setParameter(1, true).getResultStream();
	}

}
