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.MemberContactDao;
import com.apobates.forum.member.entity.MemberContact;
import com.apobates.forum.utils.Commons;

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

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

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

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

	@Override
	public Optional<MemberContact> findOneByMember(long memberId) {
		try {
			MemberContact mc = entityManager.createQuery("SELECT mc FROM MemberContact mc WHERE mc.memberId = ?1", MemberContact.class).setParameter(1, memberId).getSingleResult();
			mc.setMobile(decryptMobile(mc.getMobile(), mc.getMobileCrc32()));
			return Optional.ofNullable(mc);
		}catch(javax.persistence.NoResultException e) {
			if(logger.isDebugEnabled()){
				logger.debug(e.getMessage(), e);
			}
		}
		return Optional.empty();
	}
	
	private String decryptMobile(String encryptMobile, String mobileCrc32) {
		if (!Commons.isNotBlank(encryptMobile) || "*".equals(encryptMobile)) {
			return "";
		}
		return Commons.desDecrypt(mobileCrc32, encryptMobile, () -> "*");
	}
}
