package com.red.circle.live.app.command.user;

import com.red.circle.component.redis.service.RedisService;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.ResponseErrorCode;
import com.red.circle.live.app.dto.cmd.HeartbeatStatusEnum;
import com.red.circle.live.app.dto.cmd.HeartbeatUploadCmd;
import com.red.circle.live.domain.gateway.LiveMicrophoneGateway;
import com.red.circle.live.domain.online.LiveRoomUser;
import com.red.circle.mq.business.model.event.user.UserHeartbeatEvent;
import com.red.circle.mq.rocket.business.producer.UserMqMessageService;
import com.red.circle.tool.core.parse.DataTypeUtils;
import com.red.circle.tool.core.regex.RegexConstant;
import com.red.circle.tool.core.text.StringUtils;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 心跳上传.
 *
 * @author pengliang on 2023/12/12
 */
@Component
@RequiredArgsConstructor
public class HeartbeatUploadCmdExe {

  private final RedisService redisService;
  private final UserMqMessageService userMqMessageService;
  private final LiveMicrophoneGateway liveMicrophoneGateway;

  public void execute(HeartbeatUploadCmd cmd) {
    ResponseAssert.notNull(ResponseErrorCode.REQUEST_PARAMETER_ERROR,
        HeartbeatStatusEnum.toEnum(cmd.getStatus()));

    // 实时加入房间
    if (StringUtils.isNotBlank(cmd.getSessionId())
        && cmd.getSessionId().trim().matches(RegexConstant.NUMBER)) {
      liveMicrophoneGateway.addRoomOnlineUser(
          DataTypeUtils.toLong(cmd.getSessionId()),
          new LiveRoomUser()
              .setUserId(cmd.requiredReqUserId())
              .setWeights(0)
              .updateLastActivityTime()
      );
    }

    // 如果是定时触发, 限流15s 1次
    if (Objects.equals(cmd.getTask(), Boolean.TRUE)
        && !redisService.setIfAbsent("UHU:" + cmd.requiredReqUserId(), 1, 15, TimeUnit.SECONDS)) {
      return;
    }

    UserHeartbeatEvent userHeartbeatEvent = new UserHeartbeatEvent();
    userHeartbeatEvent.setSessionId(cmd.getSessionId());
    userHeartbeatEvent.setTask(cmd.getTask());
    userHeartbeatEvent.setUserId(cmd.requiredReqUserId());
    userHeartbeatEvent.setStatus(cmd.getStatus());
    userHeartbeatEvent.setUpMick(cmd.getUpMick());
    userHeartbeatEvent.setSysOrigin(cmd.requireReqSysOriginEnum());
    userHeartbeatEvent.setReqTrackId(cmd.getReqTraceId());
    userMqMessageService.sendUserHeartbeat(userHeartbeatEvent);

  }

}
