package com.eactive.eai.authoutbound;

import com.eactive.eai.authoutbound.mapper.OutboundOAuthCredentialMapper;
import com.eactive.eai.common.authoutbound.loader.OutboundOAuthCredentialLoader;
import com.eactive.eai.common.dao.BaseDAO;
import com.eactive.eai.common.dao.DAOException;
import com.eactive.eai.common.exception.ExceptionUtil;
import com.eactive.eai.common.lifecycle.LifecycleVO;
import com.eactive.eai.common.property.PropGroupVO;
import com.eactive.eai.common.seed.Seed;
import com.eactive.eai.common.util.Logger;
import com.eactive.eai.data.entity.onl.authoutbound.OutboundOAuthCredential;
import com.eactive.eai.data.entity.onl.lifecycle.LifeCycle;
import com.eactive.eai.data.entity.onl.property.PropGroup;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class OutboundOAuthCredentialDao extends BaseDAO {
    private static Logger logger = Logger.getLogger(Logger.LOGGER_DEFAULT);

    @Autowired
    OutboundOAuthCredentialLoader outboundOAuthCredentialLoader ;

    @Autowired
    OutboundOAuthCredentialMapper outboundOAuthCredentialMapper ;

    public List<OutboundOAuthCredentialVo> getAllOutboundOAuthCredentials() throws DAOException{
        List<OutboundOAuthCredentialVo> list = new ArrayList<>();
        try {
            List<OutboundOAuthCredential> outboundOAuthCredentials = outboundOAuthCredentialLoader.findAll();
            for (OutboundOAuthCredential outboundOAuthCredential : outboundOAuthCredentials) {
                OutboundOAuthCredentialVo vo = outboundOAuthCredentialMapper.toVo(outboundOAuthCredential);
                decryptClientSecret(vo);
                list.add(vo);
            }
        } catch (Exception e) {
            logger.error("dao", e);
            throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICLC101"));
        }
        return list;
    }

    public OutboundOAuthCredentialVo getOutboundOAuthCredential(String adapterGroupName) throws DAOException{
        try {
            OutboundOAuthCredential outboundOAuthCredential = outboundOAuthCredentialLoader.getById(adapterGroupName);
            OutboundOAuthCredentialVo vo = outboundOAuthCredentialMapper.toVo(outboundOAuthCredential);
            decryptClientSecret(vo);
            return vo;
        } catch (Exception e) {
            logger.error("dao", e);
            throw new DAOException(ExceptionUtil.getErrorCode(e, "RECEAICLC101"));
        }
    }

    public void decryptClientSecret(OutboundOAuthCredentialVo vo) throws Exception {
        String clientSecret = vo.getClientSecret();
        if (StringUtils.isNotBlank(clientSecret)) {
            String decrypted = Seed.decrypt(clientSecret);
            vo.setClientSecret(decrypted);
        }
    }
}
