package com.apobates.forum.member.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.member.api.dao.MemberLevelDao;
import com.apobates.forum.member.entity.MemberLevel;


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

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

	@Override
	public long count() {
		return -1L;
	}
	
	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public int editStatus(Integer id, boolean status) {
		return entityManager.createQuery("UPDATE MemberLevel ml SET ml.status = ?1 WHERE ml.status = ?2 AND ml.id = ?3 ")
							.setParameter(1, status)
							.setParameter(2, !status)
							.setParameter(3, id)
							.executeUpdate();
		
	}

	@Override
	public Stream<MemberLevel> findAllUsed() {
		return entityManager.createQuery("SELECT ml FROM MemberLevel ml WHERE ml.status = ?1 ORDER BY ml.minScore ASC", MemberLevel.class).setParameter(1, true).getResultStream();
	}
	
}
