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

@Repository
public class TopicTagSHistoryDaoImpl implements TopicTagSHistoryDao{
	@PersistenceContext
	private EntityManager entityManager;
	private final static Logger logger = LoggerFactory.getLogger(TopicTagSHistoryDaoImpl.class);
	
	@Override
	public Page<TopicTagSHistory> findAll(Pageable pageable) {
		final long total = count();
		if (total == 0) {
			return emptyResult();
		}
		TypedQuery<TopicTagSHistory> query = entityManager.createQuery("SELECT tth FROM TopicTagSHistory tth ORDER BY tth.id DESC", TopicTagSHistory.class);
		query.setFirstResult(pageable.getOffset());
		query.setMaxResults(pageable.getPageSize());

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

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

	@Override
	public Optional<TopicTagSHistory> findOne(Long primaryKey) {
		return Optional.ofNullable(entityManager.find(TopicTagSHistory.class, primaryKey));
	}

	@Override
	public Optional<Boolean> edit(TopicTagSHistory updateEntity) {
		return Optional.empty();
	}

	@Override
	public Stream<TopicTagSHistory> findAll() {
		return Stream.empty();
	}

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

	@Override
	public Stream<TopicTagSHistory> findAllRelate(String word, int size) {
		String tmp = Commons.htmlPurifier(word);
		return entityManager.createQuery("SELECT tth FROM TopicTagSHistory tth WHERE LOCATE(?1, tth.word)>0", TopicTagSHistory.class).setParameter(1, tmp).setMaxResults(size).getResultStream();
	}
}
