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.TopicCategoryDao;
import com.apobates.forum.core.entity.TopicCategory;
import com.apobates.forum.utils.persistence.Page;
import com.apobates.forum.utils.persistence.Pageable;

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

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

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

			@Override
			public Stream<TopicCategory> getResult() {
				return result;
			}
		};
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public void save(TopicCategory entity) {
		entityManager.persist(entity);
	}

	@Override
	public Optional<TopicCategory> findOne(Integer primaryKey) {
		if (primaryKey == 0) {
			return Optional.empty();
		}
		return Optional.ofNullable(entityManager.find(TopicCategory.class, primaryKey));
	}

	@Transactional(propagation = Propagation.REQUIRED)
	@Override
	public Optional<Boolean> edit(TopicCategory 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<TopicCategory> findAll() {
		return Stream.empty();
	}

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

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

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

}
