package com.red.circle.other.app.command.room;

import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.framework.core.response.ResponseErrorCode;
import com.red.circle.live.inner.endpoint.LiveMicClient;
import com.red.circle.other.app.convertor.live.RoomProfileAppConvertor;
import com.red.circle.other.app.dto.cmd.room.UpdateRoomSettingCmd;
import com.red.circle.other.infra.database.mongo.entity.live.RoomProfileManager;
import com.red.circle.other.infra.database.mongo.service.live.RoomProfileManagerService;
import com.red.circle.other.infra.database.mongo.service.sys.ApiOperationLogService;
import com.red.circle.other.inner.asserts.RoomErrorCode;
import java.util.Objects;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 修改房间设置信息
 *
 * @author houyong on 2020/12/4
 */
@Component
@RequiredArgsConstructor
public class UpdateRoomSettingCmdExe {

  private final LiveMicClient liveMicClient;
  private final ApiOperationLogService apiOperationLogService;
  private final RoomProfileAppConvertor roomProfileAppConvertor;
  private final RoomProfileManagerService roomProfileManagerService;

  public void execute(UpdateRoomSettingCmd cmd) {

//    apiOperationLogService.add(
//        new ApiOperationLog()
//            .setId(IdWorkerUtils.getIdStr())
//            .setRequestUserId(cmd.requiredReqUserId())
//            .setApiDesc("房间设置变更")
//            .setBusinessCode("ROOM_SETTING_UPDATE")
//            .setBusinessContent(Objects.toString(cmd.getRoomId()))
//            .setCmd(JacksonUtils.toJson(cmd))
//            .setExpiredTime(DateUtils.nowPlusDays(7))
//            .setCreateTime(DateUtils.now())
//    );

    RoomProfileManager roomProfile = roomProfileManagerService.getById(cmd.getRoomId());
    ResponseAssert.notNull(RoomErrorCode.ROOM_NOT_EXISTS, roomProfile);
    ResponseAssert.isTrue(CommonErrorCode.INSUFFICIENT_PERMISSION,
        cmd.reqIsSelf(roomProfile.getUserId()));

    if (Objects.nonNull(cmd.getJoinGolds()) && !cmd.checkJoinGoldsIsPass()) {
      ResponseAssert.failure(ResponseErrorCode.REQUEST_PARAMETER_ERROR,
          "joinGolds error, range 1~10000");
    }

    roomProfileManagerService.updateSelectiveSetting(cmd.getRoomId(),
        roomProfileAppConvertor.toRoomSetting(cmd));

    if (Objects.nonNull(cmd.getMikeSize()) && !Objects.equals(
        roomProfile.getSetting().getMikeSize(), cmd.getMikeSize())) {
      liveMicClient.updateMickSize(roomProfile.getId(), cmd.getMikeSize());
    }

  }
}
