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

import com.red.circle.common.business.dto.cmd.app.AppIdLongCmd;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
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.GameKtvUserSongCountService;
import com.red.circle.other.infra.database.mongo.service.game.GameKtvUserWeekRankCountService;
import com.red.circle.tool.core.collection.CollectionUtils;
import java.util.List;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * KTV 结束播放的歌曲.
 *
 * @author pengshigang on 2023/5/6
 */
@Component
@RequiredArgsConstructor
public class GameKtvSongEndExe {

  private final GameKtvCacheService gameKtvCacheService;
  private final GameKtvUserSongCountService gameKtvUserSongCountService;
  private final GameKtvUserWeekRankCountService gameKtvUserWeekRankCountService;

  public void execute(AppIdLongCmd cmd) {

    GameKtvUserSongCount song = gameKtvUserSongCountService.getById(cmd.getId());
    ResponseAssert.notNull(CommonErrorCode.NOT_FOUND_RECORD_INFO, song);
    if (Objects.equals(song.getStatus(), "END")) {
      return;
    }
    gameKtvUserSongCountService.updateStatus(song.getId(), "END");

    // 是否达到每日免费积分获得上限
    if (Boolean.FALSE.equals(gameKtvCacheService.isFreeIntegralMax(song.getUserId()))) {
      // 唱完则给歌单额外给100人气
      gameKtvUserWeekRankCountService
          .incExtra(song.getRegionId(), song.getUserId(), cmd.getReqSysOrigin().getOrigin());
    }

    // 开启新的一轮等待
    List<GameKtvUserSongCount> songs = listExistSong(song);
    if (CollectionUtils.isNotEmpty(songs)) {
      gameKtvUserSongCountService.updateStatus(songs.get(0).getId(), "WAIT");
    }
    gameKtvCacheService.cacheWaitCountDown(song.getRoomId());
    gameKtvCacheService.removeSongCountDown(song.getRoomId());
  }

  private List<GameKtvUserSongCount> listExistSong(GameKtvUserSongCount song) {

    return gameKtvUserSongCountService.list(song.getSysOrigin(), song.getRoomId());
  }

}
