
package com.tmerclub.cloud.live.controller.app;

import cn.hutool.core.util.StrUtil;
import com.tmerclub.cloud.api.platform.config.FeignShopConfig;
import com.tmerclub.cloud.common.bean.AliLive;
import com.tmerclub.cloud.common.exception.LuckException;
import com.tmerclub.cloud.common.response.ServerResponseEntity;
import com.tmerclub.cloud.common.security.AuthUserContext;
import com.tmerclub.cloud.live.service.LiveRoomService;
import com.tmerclub.cloud.live.util.AliLiveUtil;
import com.tmerclub.cloud.live.vo.LiveRoomVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;


/**
 * @author TRAKC
 */
@RestController("MyLiveRoomController")
@RequestMapping("/live/liveRoom")
@Tag(name = "我的直播接口")
public class MyLiveRoomController {

    @Autowired
    private LiveRoomService liveRoomService;
    @Autowired
    private FeignShopConfig feignShopConfig;

    @GetMapping("/get_user_living_room")
    @Operation(summary = "主播获取当前正在开播的直播间信息")
    public ServerResponseEntity<LiveRoomVO> getUserLivingRoom() {
        Long userId = AuthUserContext.get().getUserId();
        LiveRoomVO livingRoom = getLivingRoom(userId);
        return ServerResponseEntity.success(livingRoom);
    }

    private LiveRoomVO getLivingRoom(Long userId) {
        LiveRoomVO livingRoom = liveRoomService.getByUserId(userId);
        if (Objects.isNull(livingRoom)) {
            throw new LuckException("当前未有直播权限");
        }
        long currentTimeMillis = System.currentTimeMillis();
        if (livingRoom.getStartTime().getTime() > currentTimeMillis) {
            throw new LuckException("未到直播开始时间");
        }
        return livingRoom;
    }

    @GetMapping("/get_push_url")
    @Operation(summary = "获取推流地址", description = "获取推流地址")
    public ServerResponseEntity<String> getPushUrl() {
        AliLive aliLive = feignShopConfig.getAliLive();
        if (Objects.isNull(aliLive) || StrUtil.isBlank(aliLive.getAppName())) {
            throw new LuckException("无法获取到直播配置");
        }
        Long userId = AuthUserContext.get().getUserId();
        LiveRoomVO livingRoom = getLivingRoom(userId);
        // 不超过256字符 支持数字、大小写字母、短划线(-)、下划线(_)、等号(=)
        // {appName}-{roomId}-{shopId}-{userId}
        String streamName = StrUtil.format("{}-{}-{}-{}", aliLive.getAppName(), livingRoom.getRoomId(), livingRoom.getShopId(), livingRoom.getUserId());
        String pushUrl = AliLiveUtil.getPushUrl(streamName, livingRoom.getEndTime(), aliLive);
        return ServerResponseEntity.success(pushUrl);
    }
}
