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.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.apobates.forum.member.api.dao.MemberSocialInfoDao;
import com.apobates.forum.member.entity.MemberSocialInfo;
import com.apobates.forum.utils.Commons;

@Repository
public class MemberSocialInfoDaoImpl implements MemberSocialInfoDao{
	@PersistenceContext
	private EntityManager entityManager;
	@Value("${site.dec.salt}")
	private String globalDecSalt;
	private final static Logger logger = LoggerFactory.getLogger(MemberSocialInfoDaoImpl.class);

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

	@Override
	public Optional<MemberSocialInfo> findOne(Long primaryKey) {
		MemberSocialInfo msi = entityManager.find(MemberSocialInfo.class, primaryKey);
		msi.setEmail(decryptEnail(msi.getEmail(), msi.getMemberNames()));
		return Optional.ofNullable(msi);
	}
	
	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public Optional<Boolean> edit(MemberSocialInfo 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<MemberSocialInfo> findAll() {
		return Stream.empty();
	}

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

	@Override
	public Optional<MemberSocialInfo> findOneByMember(long memberId) {
		try {
			MemberSocialInfo msi = entityManager.createQuery("SELECT msi FROM MemberSocialInfo msi WHERE msi.memberId = ?1", MemberSocialInfo.class).setParameter(1, memberId).getSingleResult();
			msi.setEmail(decryptEnail(msi.getEmail(), msi.getMemberNames()));
			return Optional.ofNullable(msi);
		}catch(javax.persistence.NoResultException e) {
			if(logger.isDebugEnabled()){
				logger.debug(e.getMessage(), e);
			}
		}
		return Optional.empty();
	}

	@Override
	public Optional<MemberSocialInfo> findOneByMember(String memberNames, String encryptEmailString) {
		try {
			MemberSocialInfo msi = entityManager.createQuery("SELECT msi FROM MemberSocialInfo msi WHERE msi.memberNames = ?1 AND msi.email = ?2", MemberSocialInfo.class)
					.setParameter(1, memberNames)
					.setParameter(2, encryptEmailString)
					.getSingleResult();
			return Optional.ofNullable(msi);
		}catch(javax.persistence.NoResultException e) {
			if(logger.isDebugEnabled()){
				logger.debug(e.getMessage(), e);
			}
		}
		return Optional.empty();
	}
	
	private String decryptEnail(String encryptEmail, String memberNames) {
		if (!Commons.isNotBlank(encryptEmail) || "*".equals(encryptEmail)) {
			return "";
		}
		String secretString = String.format("%s/%s", globalDecSalt, memberNames);
		return Commons.desDecrypt(secretString, encryptEmail, () -> "*");
	}
}
