package com.red.circle.external.inner.service.message.impl;

import com.red.circle.common.business.dto.rtc.RtcCredentialCO;
import com.red.circle.common.business.dto.rtc.RtcProviderEnum;
import com.red.circle.component.instant.msg.InstantMessageProperties;
import com.red.circle.component.instant.msg.tencet.props.TrtcTencetProperties;
import com.red.circle.component.instant.msg.tencet.service.endpoint.api.trtc.TencentTrtcService;
import com.red.circle.external.inner.model.cmd.message.TrtcRemoveUserCmd;
import com.red.circle.external.inner.model.cmd.message.TrtcUserBlockedCmd;
import com.red.circle.external.inner.service.message.TrtcClientService;
import com.red.circle.framework.core.asserts.ResponseAssert;
import com.red.circle.framework.core.response.CommonErrorCode;
import com.red.circle.other.inner.endpoint.user.user.UserProfileClient;
import com.red.circle.other.inner.model.dto.user.UserProfileDTO;
import com.tencentyun.TLSSigAPIv2;
import io.agora.media.RtcTokenBuilder2;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * trtc 服务.
 *
 * @author pengliang on 2023/10/17
 */
@Service
@RequiredArgsConstructor
public class TrtcClientServiceImpl implements TrtcClientService {

  private final UserProfileClient userProfileClient;
  private final TencentTrtcService tencentTrtcService;
  private final InstantMessageProperties instantMessageProperties;

  @Value("${rtc.appId}")
  private  String appId;

  @Value("${rtc.certificate}")
  private String certificate;

  @Value("${red-circle.instant-message.tencet-trtc.userSigExpireSeconds:7200}")
  private long trtcUserSigExpireSeconds;

  @Value("${red-circle.instant-message.tencet-trtc.userSigKey:${red-circle.instant-message.tencet-trtc.secretKey:}}")
  private String trtcUserSigKey;

  @Override
  public boolean removeUser(TrtcRemoveUserCmd cmd) {
    return tencentTrtcService.removeUser(cmd.getRoomId(),
        cmd.getUserIds(), cmd.getLogOrigin());
  }

  @Override
  public boolean setUserBlocked(TrtcUserBlockedCmd cmd) {
    return tencentTrtcService.setUserBlocked(cmd.getRoomId(), cmd.getUserId(), cmd.getMute());
  }

  @Override
  public boolean dismissRoom(String roomId) {
    return tencentTrtcService.dismissRoom(roomId);
  }

  @Override
  public String createAgoraToken(Long userId, String channelName) {
    UserProfileDTO userProfile = userProfileClient.getByUserId(userId).getBody();
//    return agoraAuthentication.createChannelToken(
//        channelName,
//        Integer.parseInt(userProfile.getAccount())
//    );
    RtcTokenBuilder2 var3 = new RtcTokenBuilder2();
    return var3.buildTokenWithUid(appId, certificate, channelName, Integer.parseInt(userProfile.getAccount()), RtcTokenBuilder2.Role.ROLE_SUBSCRIBER, 21600, 21600);
  }

  @Override
  public String createAgoraTokenGoUp(Long userId, String channelName) {
    UserProfileDTO userProfile = userProfileClient.getByUserId(userId).getBody();
    RtcTokenBuilder2 var3 = new RtcTokenBuilder2();
    return var3.buildTokenWithUid(appId, certificate, channelName, Integer.parseInt(userProfile.getAccount()), RtcTokenBuilder2.Role.ROLE_PUBLISHER, 21600, 21600);
  }

  @Override
  public RtcCredentialCO createTrtcCredential(Long userId, String roomIdentifier,
      Boolean publisher) {
    ResponseAssert.notNull(CommonErrorCode.REQUIRED_FIELDS_CANNOT_BE_IGNORED, userId);
    ResponseAssert.isTrue(CommonErrorCode.REQUIRED_FIELDS_CANNOT_BE_IGNORED,
        StringUtils.hasText(roomIdentifier));

    TrtcTencetProperties trtcProperties = instantMessageProperties.getTencetTrtc();
    ResponseAssert.notNull(CommonErrorCode.CONFIGURATION_ERROR, trtcProperties);
    ResponseAssert.notNull(CommonErrorCode.CONFIGURATION_ERROR, trtcProperties.getSdkAppId());
    ResponseAssert.isTrue(CommonErrorCode.CONFIGURATION_ERROR, StringUtils.hasText(trtcUserSigKey));

    String trtcUserId = userId.toString();
    String userSig = new TLSSigAPIv2(
        trtcProperties.getSdkAppId(),
        trtcUserSigKey
    ).genUserSig(trtcUserId, trtcUserSigExpireSeconds);

    RtcCredentialCO credential = new RtcCredentialCO()
        .setRtcProvider(RtcProviderEnum.TRTC.name())
        .setTrtcSdkAppId(trtcProperties.getSdkAppId())
        .setTrtcUserId(trtcUserId)
        .setTrtcUserSig(userSig)
        .setTrtcRole(Boolean.TRUE.equals(publisher) ? 20 : 21)
        .setTrtcUserSigExpireSeconds(trtcUserSigExpireSeconds)
        .setTrtcUserSigExpireAt(
            System.currentTimeMillis() + trtcUserSigExpireSeconds * 1000L);
    applyTrtcRoomIdentifier(credential, roomIdentifier);
    return credential;
  }

  private void applyTrtcRoomIdentifier(RtcCredentialCO credential, String roomIdentifier) {
    String normalizedRoomIdentifier = roomIdentifier.trim();
    try {
      credential.setTrtcRoomId(Long.valueOf(normalizedRoomIdentifier));
    } catch (NumberFormatException ignored) {
      credential.setTrtcStrRoomId(normalizedRoomIdentifier);
    }
  }

}
