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

import com.alibaba.fastjson.JSON;
import com.red.circle.common.business.dto.cmd.app.AppRoomIdCmd;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.live.domain.live.LiveMusicStatus;
import com.red.circle.live.infra.database.cache.service.LiveMusicHeartbeatService;
import java.util.Objects;

import com.red.circle.tool.core.text.StringUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
//import org.redisson.api.RLock;
//import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

/**
 * 移除房间播放音乐.
 *
 * @author pengliang on 2024/1/8
 */

@Slf4j
@Component
@RequiredArgsConstructor
public class LiveMusicRemoveCmdExe {

  private final LiveMusicHeartbeatService liveMusicHeartbeatService;
//  private final RedissonClient redissonClient;

  public void execute(AppRoomIdCmd cmd) {
//      RLock lock = redissonClient.getLock(cmd.getRoomId().toString()+"music");
//      lock.lock();
      String musicUserInfo = liveMusicHeartbeatService.getMusicUserInfo(cmd.getRoomId());
      try {
          if (Objects.isNull(musicUserInfo)){
              ResponseAssert.isTrue(CommonErrorCode.INSUFFICIENT_PERMISSION, false);
          }
          if (StringUtils.isBlank(musicUserInfo)){
              ResponseAssert.isTrue(CommonErrorCode.INSUFFICIENT_PERMISSION, false);
          }
          LiveMusicStatus musicUser = JSON.parseObject(musicUserInfo, LiveMusicStatus.class);
          ResponseAssert.isTrue(CommonErrorCode.INSUFFICIENT_PERMISSION,
                  Objects.equals(musicUser.getUserId(), cmd.requiredReqUserId()));
          liveMusicHeartbeatService.removeMickUser(cmd.getRoomId());
      }catch (Exception e){
          ResponseAssert.isTrue(CommonErrorCode.INSUFFICIENT_PERMISSION, false);
      }finally {
//          lock.unlock();
      }
  }

}
