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

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

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

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

	@Override
	public Stream<SmileyThemePicture> findAllByTheme(int smileyThemeId) {
		return entityManager.createQuery("SELECT stp FROM SmileyThemePicture stp WHERE stp.smileyThemeId = ?1", SmileyThemePicture.class).setParameter(1, smileyThemeId).getResultStream();
	}

	@Override
	public Stream<SmileyThemePicture> findAllByTheme(String smileyThemeNames) {
		return entityManager.createQuery("SELECT stp FROM SmileyThemePicture stp WHERE stp.smileyThemeDirectNames = ?1", SmileyThemePicture.class).setParameter(1, smileyThemeNames).getResultStream();
	}

	@Override
	public Optional<SmileyThemePicture> findOne(int themeId, String picFileNames) {
		try {
			SmileyThemePicture stp = entityManager.createQuery("SELECT stp FROM SmileyThemePicture stp WHERE stp.smileyThemeId = ?1 AND stp.fileNames = ?2", SmileyThemePicture.class).setParameter(1, themeId).setParameter(2, picFileNames).getSingleResult();
			return Optional.ofNullable(stp);
		}catch(javax.persistence.NoResultException e) {
			if(logger.isDebugEnabled()){
				logger.debug(e.getMessage(), e);
			}
		}
		return Optional.empty();
	}

}
