package io.wdd.rpc.message.handler;

import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import io.wdd.rpc.message.OctopusMessage;
import io.wdd.rpc.message.OctopusMessageType;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.SuperBuilder;

import java.time.LocalDateTime;
import java.util.concurrent.CountDownLatch;

import static io.wdd.rpc.message.handler.OMessageHandler.GenerateOMessageMatchKey;

@Data
@AllArgsConstructor
@NoArgsConstructor
@SuperBuilder(toBuilder = true)
@ApiModel("众多业务调用RPC,异步等待需要确定返回消息是谁的")
public class OMessageReplayContent {

    @ApiModelProperty("rpc消息的类型")
    OctopusMessageType octopusMessageType;

    @ApiModelProperty("rpc消息发送的时间, 精确匹配,去掉毫秒")
    @JsonFormat(pattern = "yyyy-MM-dd hh:MM:ss")
    LocalDateTime initTime;

    @ApiModelProperty("rpc消息-匹配唯一key")
    String replayMatchKey;

    @ApiModelProperty("需要等待的消息个数")
    CountDownLatch countDownLatch;

    @ApiModelProperty("发送的OctopusMessage")
    OctopusMessage originOMessage;


    public static OMessageReplayContent build(OctopusMessage originOMessage, int waitForReplayNum) {

        CountDownLatch latch = null;
        if (waitForReplayNum != 0) {
            latch = new CountDownLatch(waitForReplayNum);
        }

        return new OMessageReplayContent(
                originOMessage.getOctopusMessageType(),
                originOMessage.getInit_time(),
                GenerateOMessageMatchKey(
                        originOMessage.getOctopusMessageType(),
                        originOMessage.getInit_time()
                ),
                latch,
                originOMessage
        );
    }

}
