package com.liquidnet.service.consumer.order.receiver;

import com.liquidnet.commons.lang.util.CollectionUtil;
import com.liquidnet.commons.lang.util.JsonUtils;
import com.liquidnet.service.base.ResponseDto;
import com.liquidnet.service.base.constant.MQConst;
import com.liquidnet.service.consumer.order.service.processor.ConsumerGalaxyJsonNftPublishAndBuyProcessor;
import com.liquidnet.service.galaxy.dto.param.GalaxyNftPublishAndBuyReqDto;
import com.liquidnet.service.galaxy.dto.param.GalaxyNftPublishAndBuyRespDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Slf4j
@Component
public class ConsumerGalaxyJsonNftPublishAndBuyReceiver extends AbstractBizRedisReceiver {
    @Autowired
    private ConsumerGalaxyJsonNftPublishAndBuyProcessor jsonNftPublishAndBuyProcessor;

    @Override
    protected boolean consumerMessageHandler(String msg) {
        boolean aBoolean = false;
        try {
            GalaxyNftPublishAndBuyReqDto textMessage = JsonUtils.fromJson(msg, GalaxyNftPublishAndBuyReqDto.class);
            if (textMessage == null) {
                aBoolean = true;
            } else {
                //执行计数
                ResponseDto<GalaxyNftPublishAndBuyRespDto> responseDto = jsonNftPublishAndBuyProcessor.nftPublishAndBuy(textMessage);
                if(responseDto.isSuccess()){
                    aBoolean = true;
                }
            }
        } catch (Exception e) {
            log.error("CONSUMER MSG EX_HANDLE ==> [{}]:{}", this.getRedisStreamKey(), msg, e);
        } finally {
            if (!aBoolean) {
                HashMap<String, String> map = CollectionUtil.mapStringString();
                map.put("message", msg);
                stringRedisTemplate.opsForStream().add(StreamRecords.mapBacked(map).withStreamKey(this.getRedisStreamKey()));
            }
        }
        return aBoolean;
    }

    @Override
    protected String getRedisStreamKey() {
        return MQConst.GalaxyQueue.JSON_NFT_PUBLISH_AND_BUY.getKey();
    }

    @Override
    protected String getRedisStreamGroup() {
        return MQConst.GalaxyQueue.JSON_NFT_PUBLISH_AND_BUY.getGroup();
    }
}
