package com.inspect.ivs.service;

import com.inspect.base.core.constant.Color;
import com.inspect.ivs.config.ZlMediaConfig;
import com.inspect.ivs.constant.ZlMediaConst;
import com.inspect.ivs.domain.ZlmConvertUrl;
import com.inspect.ivs.view.IvsVideoRtspView;
import com.inspect.ivs.vo.ZlMediaRtspVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;

@Component
public class ZlMediaComponent extends IvsCommonService {
   private static final Logger log = LoggerFactory.getLogger(ZlMediaComponent.class);
   private final ZlMediaConfig zlMediaConfig;

   public ZlMediaComponent(ZlMediaConfig zlMediaConfig) {
      this.zlMediaConfig = zlMediaConfig;
   }

   public String getAddress() {
      return this.zlMediaConfig.getUrl();
   }

   public void convert(String rtspUrl, String streamId, IvsVideoRtspView ivsVideoRtspView) {
      if(zlMediaConfig.isEnable()) {
         log.info(Color.YELLOW + "zlMediaConfig: {}" + Color.END, zlMediaConfig);
         ZlMediaRtspVo rtspVo = new ZlMediaRtspVo(zlMediaConfig.getSecret(),
                 streamId,
                 rtspUrl);
         log.debug("[GAB] rtspVo: {}", rtspVo);
         String block = this.http(HttpMethod.POST, ZlMediaConst.CONVERT_RTSP_URL)
                 .header("Accept", new String[]{"*/*"})
                 .header("Accept-Encoding", new String[]{"gzip, deflate, br"})
                 .header("Connection", new String[]{"keep-alive"})
                 .header("Postman-Token", "93a405a2-2d6f-4c58-b085-d73badbe7331")
                 .bodyValue(rtspVo)
                 .retrieve()
                 .bodyToMono(String.class)
                 .block();
         log.debug("[GAB] ZL-MEDIA Convert:");
         log.debug("{}", block);
         ZlmConvertUrl zlmConvertUrl = new ZlmConvertUrl(zlMediaConfig.getUrl(), zlMediaConfig.getWebrtcPrefix(), streamId);
         ivsVideoRtspView.setWebrtcURL(zlmConvertUrl.getWebrtc());
         ivsVideoRtspView.setHlsURL(zlmConvertUrl.getM3u8());
         ivsVideoRtspView.setFlvURL(zlmConvertUrl.getFlv());
         ivsVideoRtspView.setMp4URL(zlmConvertUrl.getMp4());
      }
   }
}
