package cn.datax.service.data.market.service.impl;

import cn.datax.common.core.DataConstant;
import cn.datax.common.utils.MD5Util;
import cn.datax.common.utils.SecurityUtil;
import cn.datax.service.data.market.api.entity.DataApiEntity;
import cn.datax.service.data.market.api.vo.ApiHeader;
import cn.datax.service.data.market.config.MappingHandlerMapping;
import cn.datax.service.data.market.dao.DataApiDao;
import cn.datax.service.data.market.service.ApiExecuteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

@Service
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true, rollbackFor = Exception.class)
public class ApiExecuteServiceImpl implements ApiExecuteService {

    @Autowired
    private MappingHandlerMapping mappingHandlerMapping;

    @Autowired
    private DataApiDao dataApiDao;

    @Override
    public ApiHeader getApiHeader(String id) {
        ApiHeader apiHeader = new ApiHeader();
        try {
            MD5Util mt = MD5Util.getInstance();
            apiHeader.setApiKey(mt.encode(id));
            apiHeader.setSecretKey(mt.encode(SecurityUtil.getUserId()));
        } catch (Exception e) {
        }
        return apiHeader;
    }

    @Override
    public void registerApi(String id) {
        DataApiEntity dataApiEntity = dataApiDao.selectById(id);
        if (dataApiEntity != null) {
            mappingHandlerMapping.registerMapping(dataApiEntity);
            dataApiEntity.setStatus(DataConstant.ApiState.PUBLISHED.getKey());
            dataApiDao.updateById(dataApiEntity);
        }
    }

    @Override
    public void unRegisterApi(String id) {
        DataApiEntity dataApiEntity = dataApiDao.selectById(id);
        if (dataApiEntity != null) {
            mappingHandlerMapping.unregisterMapping(dataApiEntity);
            dataApiEntity.setStatus(DataConstant.ApiState.OFFLINE.getKey());
            dataApiDao.updateById(dataApiEntity);
        }
    }
}
