package com.tuoheng.admin.service.inspection.update.flyer;

import com.tuoheng.admin.dto.StreamingDto;
import com.tuoheng.common.core.exception.ServiceException;
import com.tuoheng.common.core.utils.JsonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Locale;

@Slf4j
@Service
public class GetLiveStatusService {

    @Autowired
    @Qualifier("restTemplate")
    private RestTemplate restTemplate;

    @Value("${tuoheng.live-channel-domain-url:}")
    private String channel_url;

    public StreamingDto getLiveStatus(String code) {
        if (org.apache.commons.lang3.StringUtils.isEmpty(code)) {
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "通道编码不能为空！");
        }
        String url = String.format(Locale.ENGLISH, "%s%s", channel_url, LiveChannelConstant.GET_LIVE_CHANNEL_INFO);
        ParameterizedTypeReference<JsonResult<StreamingDto>> parameterizedTypeReference =
                new ParameterizedTypeReference<JsonResult<StreamingDto>>() {
                };
        ResponseEntity<JsonResult<StreamingDto>> response;
        try {
            response = restTemplate.exchange(url, HttpMethod.GET, null, parameterizedTypeReference, code);
        } catch (Exception e) {
            log.error("", e);
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "获取通道状态失败!");
        }
        if (response == null || !response.hasBody() || response.getBody().getCode() != JsonResult.SUCCESS) {
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "获取通道状态失败!");
        }
        StreamingDto liveChannelDto = response.getBody().getData();
        if (liveChannelDto == null || org.apache.commons.lang3.StringUtils.isEmpty(liveChannelDto.getCode())
                || liveChannelDto.getStatus() == null
                || org.apache.commons.lang3.StringUtils.isEmpty(liveChannelDto.getPushUrl())
                || org.apache.commons.lang3.StringUtils.isEmpty(liveChannelDto.getPullUrl())) {
            log.error("获取通道状态信息不完整!");
            throw new ServiceException(HttpStatus.BAD_REQUEST.value(), "获取通道状态信息不完整!");
        }
        return liveChannelDto;
    }

}
