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 javax.persistence.TypedQuery;
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.TopicCategoryItemDao;
import com.apobates.forum.core.entity.TopicCategoryItem;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.Pageable;

@Repository
public class TopicCategoryItemDaoImpl implements TopicCategoryItemDao{
	@PersistenceContext
	private EntityManager entityManager;
	private final static Logger logger = LoggerFactory.getLogger(TopicCategoryItemDaoImpl.class);

	@Override
	public Page<TopicCategoryItem> findAll(Pageable pageable) {
		final long total = count();
		if (total == 0) {
			return emptyResult();
		}
		TypedQuery<TopicCategoryItem> query = entityManager.createQuery("SELECT tci FROM TopicCategoryItem tci ORDER BY tci.id DESC", TopicCategoryItem.class);
		query.setFirstResult(pageable.getOffset());
		query.setMaxResults(pageable.getPageSize());

		final Stream<TopicCategoryItem> result = query.getResultStream();
		return new Page<TopicCategoryItem>() {
			@Override
			public long getTotalElements() {
				return total;
			}

			@Override
			public Stream<TopicCategoryItem> getResult() {
				return result;
			}
		};
	}
	
	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void save(TopicCategoryItem entity) {
		entityManager.persist(entity);
	}

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

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

	@Override
	public Stream<TopicCategoryItem> findAllByCategory(int categoryId) {
		return entityManager.createQuery("SELECT tci FROM TopicCategoryItem tci WHERE tci.topicCategoryId = ?1", TopicCategoryItem.class).setParameter(1, categoryId).getResultStream();
	}

}
