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

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

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

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public Optional<Boolean> edit(SmileyTheme 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<SmileyTheme> findAll() {
		return entityManager.createQuery("SELECT st FROM SmileyTheme st", SmileyTheme.class).getResultStream();
	}

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

	@Override
	public Optional<SmileyTheme> findOneByDirectName(String directName) {
		try {
			SmileyTheme st = entityManager.createQuery("SELECT st FROM SmileyTheme st WHERE st.directNames = ?1", SmileyTheme.class).setParameter(1, directName).getSingleResult();
			return Optional.ofNullable(st);
		}catch(javax.persistence.NoResultException e) {
			if(logger.isDebugEnabled()){
				logger.debug(e.getMessage(), e);
			}
		}
		return Optional.empty();
	}

}
