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.ForumIpAddressRuleDao;
import com.apobates.forum.member.entity.ForumIpAddressRule;

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

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

	@Override
	public long count() {
		try {
			return entityManager.createQuery("SELECT COUNT(fia) FROM ForumIpAddressRule fia", Long.class).getSingleResult();
		} catch (Exception e) {
			if (logger.isDebugEnabled()) {
				logger.debug("[count][ForumIpAddressRuleDao]", e);
			}
		}
		return 0L;
	}

	@Override
	public Stream<ForumIpAddressRule> findAll(boolean status) {
		return entityManager.createQuery("SELECT fia FROM ForumIpAddressRule fia WHERE fia.status = ?1", ForumIpAddressRule.class).setParameter(1, status).getResultStream();
	}

	@Override
	public long count(boolean status) {
		try {
			return entityManager.createQuery("SELECT COUNT(fia) FROM ForumIpAddressRule fia WHERE fia.status = ?1", Long.class).setParameter(1, status).getSingleResult();
		} catch (Exception e) {
			if (logger.isDebugEnabled()) {
				logger.debug("[count][ForumIpAddressRuleDao]", e);
			}
		}
		return 0L;
	}

}
