package com.red.circle.other.app.command.game.ktv;

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.other.app.dto.cmd.game.GameKtvClickSongCmd;
import com.red.circle.other.domain.gateway.user.ability.UserRegionGateway;
import com.red.circle.other.infra.database.cache.service.other.GameKtvCacheService;
import com.red.circle.other.infra.database.mongo.entity.game.ktv.GameKtvUserSongCount;
import com.red.circle.other.infra.database.mongo.service.game.GameKtvHotSongCountService;
import com.red.circle.other.infra.database.mongo.service.game.GameKtvUserSongCountService;
import com.red.circle.other.infra.database.rds.entity.game.GameKtvConfig;
import com.red.circle.other.infra.database.rds.service.game.GameKtvConfigService;
import com.red.circle.other.inner.asserts.GameErrorCode;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * Ktv点歌.
 *
 * @author pengshigang on 2023/5/6
 */
@Component
@RequiredArgsConstructor
public class GameKtvClickSongExe {

  private final UserRegionGateway userRegionGateway;
  private final GameKtvCacheService gameKtvCacheService;
  private final GameKtvConfigService gameKtvConfigService;
  private final GameKtvHotSongCountService gameKtvHotSongCountService;
  private final GameKtvUserSongCountService gameKtvUserSongCountService;

  public void execute(GameKtvClickSongCmd cmd) {

    GameKtvConfig gameKtvConfig = gameKtvConfigService.getById(cmd.getSongId());
    ResponseAssert.notNull(CommonErrorCode.NOT_OPEN_ERROR, gameKtvConfig);

    ResponseAssert.isFalse(GameErrorCode.TOP_LIMIT_ERROR,
        gameKtvUserSongCountService.isMaximumNumber(cmd.getRoomId(), cmd.getReqUserId()));

    String regionId = userRegionGateway.getRegionId(cmd.getReqUserId());

    // 播放中则将房间ktv定时器30重置,只有一首歌则重置等待倒计时
    String status = "NORMAL";

    if (Boolean.FALSE.equals(gameKtvUserSongCountService.existByRoomId(cmd.getRoomId()))) {
      gameKtvCacheService.cacheWaitCountDown(cmd.getRoomId());
      status = "WAIT";
    }

    // 添加到已点歌曲列表
    gameKtvUserSongCountService.add(new GameKtvUserSongCount()
        .setSysOrigin(cmd.getReqSysOrigin().getOrigin())
        .setUserId(cmd.getReqUserId())
        .setStatus(status)
        .setRoomId(cmd.getRoomId())
        .setRegionId(regionId)
        .setSongId(gameKtvConfig.getId())
    );

    // 增加热门歌曲人气值
    gameKtvHotSongCountService.add(cmd.getReqSysOrigin().getOrigin(), regionId, cmd.getSongId());

  }

}
