package io.wdd.agent.executor.reply;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.wdd.common.utils.TimeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.data.redis.connection.stream.RecordId;
import org.springframework.data.redis.connection.stream.StreamRecords;
import org.springframework.data.redis.connection.stream.StringRecord;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * 简单的发送缓存的命令执行Log到Redis的StreamKey中
 */
@Service
@Slf4j
public class SimpleStreamSender {

    @Resource
    RedisTemplate redisTemplate;

    @Resource
    ObjectMapper objectMapper;

    /**
     * 根据StreamKey 发送命令日志到Redis中
     *
     * @param streamKey 返回结果的Key
     * @return
     */
    public boolean sendLog(String streamKey, ArrayList<String> commandExecLogCachedLog) {

        return this.send(streamKey, commandExecLogCachedLog);

    }

    private boolean send(String streamKey, List<String> content) {

        try {

            String resultContent = objectMapper.writeValueAsString(content);

            // 构造Stream类型的数据结构，然后进行传输
            HashMap<String, String> map = new HashMap<>();
            map.put(TimeUtils.currentTimeString(), resultContent);

            log.debug("redis stream sender message is {}", map);

            StringRecord stringRecord = StreamRecords
                    .string(map).withStreamKey(streamKey);

            // 发送内容到Redis中
            RecordId recordId = redisTemplate.opsForStream().add(stringRecord);

            // 返回结果
            return ObjectUtils.isNotEmpty(recordId);

        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

    }

}
