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

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

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

	@Override
	public Optional<MemberRealAuthentication> findOne(Long primaryKey) {
		MemberRealAuthentication mra = entityManager.find(MemberRealAuthentication.class, primaryKey);
		mra.setIdentityCard(decryptIdentityCard(mra.getIdentityCard(), mra.getMemberId()));
		return Optional.ofNullable(mra);
	}
	
	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public Optional<Boolean> edit(MemberRealAuthentication 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<MemberRealAuthentication> findAll() {
		// TODO Auto-generated method stub
		return null;
	}

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

	@Override
	public Optional<MemberRealAuthentication> findOneByMember(long memberId) {
		try {
			MemberRealAuthentication mra = entityManager.createQuery("SELECT mra FROM MemberRealAuthentication mra WHERE mra.memberId = ?1", MemberRealAuthentication.class).setParameter(1, memberId).getSingleResult();
			mra.setIdentityCard(decryptIdentityCard(mra.getIdentityCard(), mra.getMemberId()));
			return Optional.ofNullable(mra);
		}catch(javax.persistence.NoResultException e) {
			if(logger.isDebugEnabled()){
				logger.debug(e.getMessage(), e);
			}
		}
		return Optional.empty();
	}
	
	private String decryptIdentityCard(String encryptIdentityCard, long memberId) {
		if (!Commons.isNotBlank(encryptIdentityCard) || "*".equals(encryptIdentityCard)) {
			return "";
		}
		String secretString = String.format("%sv%s", globalDecSalt, memberId);
		return Commons.desDecrypt(secretString, encryptIdentityCard, () -> "*");
	}
}
