// 获取 video 元素的宽度和高度
var videoChannelWidth;
var videoChannelHeight;
// 创建 ImageCapture 对象
var videoChannelCapture;
var usVideoElement;
var captureCanvas;

/// 初始化 imageCapture 并返回 video 宽高
/// [channel_id] 传入需要捕获的 channel_id
function initVideoCapture(channel_id) {
  try {
    // 获取video元素
    let videoChannelView = document.getElementById(
      'HTMLID_trtcCloudChannelView' + channel_id,
    );

    usVideoElement = videoChannelView.querySelector('video');
    try {
      // 获取video流
      let stream = usVideoElement.captureStream();
      let track = stream.getVideoTracks()[0];
      // 获取video的宽度和高度
      const settings = track.getSettings();
      videoChannelWidth = settings.width;
      videoChannelHeight = settings.height;
      if (!videoChannelWidth || !videoChannelHeight) {
        videoChannelWidth = usVideoElement.videoWidth;
        videoChannelHeight = usVideoElement.videoHeight;
      }

      // 创建ImageCapture对象
      videoChannelCapture = new ImageCapture(track);
    } catch (error) {
      videoChannelCapture = null;
      // 获取video元素的宽度和高度
      videoChannelWidth = usVideoElement.videoWidth;
      videoChannelHeight = usVideoElement.videoHeight;
    }

    // 初始化canvas
    captureCanvas = document.createElement('canvas');
    captureCanvas.width = videoChannelWidth;
    captureCanvas.height = videoChannelHeight;
    return [videoChannelWidth, videoChannelHeight];
  } catch (error) {
    return [0, 0];
  }
}

function setClipSize(width, height) {
  captureCanvas.width = width;
  captureCanvas.height = height;
}

/// 捕获视频帧并转换为二进制数组返回
function captureOneFrame() {
  if (videoChannelCapture == null) {
    const context = captureCanvas.getContext('2d');
    context.drawImage(
      usVideoElement,
      0,
      0,
      videoChannelWidth,
      videoChannelHeight,
    );
    const dataUrl = captureCanvas.toDataURL('image/jpeg');
    const binary = atob(dataUrl.split(',')[1]);
    const uint8Array = new Uint8Array(binary.length);
    for (let i = 0; i < binary.length; i++) {
      uint8Array[i] = binary.charCodeAt(i);
    }
    return Promise.resolve(uint8Array);
  } else {
    const promise = videoChannelCapture.grabFrame().then((imageBitmap) => {
      const context = captureCanvas.getContext('2d');
      context.drawImage(
        imageBitmap,
        0,
        0,
        videoChannelWidth,
        videoChannelHeight,
      );
      const dataUrl = captureCanvas.toDataURL('image/jpeg');
      const binary = atob(dataUrl.split(',')[1]);
      const uint8Array = new Uint8Array(binary.length);
      for (let i = 0; i < binary.length; i++) {
        uint8Array[i] = binary.charCodeAt(i);
      }
      return uint8Array;
    });
    return promise;
  }
}

/// 释放 imageCapture 对象
function disposeVideoCapture() {
  videoChannelCapture = null;
  usVideoElement = null;
  captureCanvas = null;
  console.log('videoChannelCapture has been disposed');
}

async function copyMainViewToSubView(main_id, sub_id) {
  let mainVideoElement = document.getElementById(
    'HTMLID_trtcCloudChannelView' + main_id,
  );
  let subVideoElement = document.getElementById(
    'HTMLID_trtcCloudChannelView' + sub_id,
  );
  let gotStream = false;
  let mainStream;
  try {
    mainStream = mainVideoElement.querySelector('video').captureStream();
    gotStream = true;
  } catch (error) {}
  if (!gotStream) {
    for (let i = 0; i < 5; i++) {
      try {
        mainStream = mainVideoElement.querySelector('video').captureStream();
        subVideoElement.innerHTML = '';
        let subVideo = createVideo(mainStream, sub_id);
        subVideoElement.appendChild(subVideo);
        break;
      } catch (error) {
        await new Promise((resolve) => setTimeout(resolve, 200));
      }
    }
  }
  if (gotStream) {
    subVideoElement.innerHTML = '';
    let subVideo = createVideo(mainStream, sub_id);
    subVideoElement.appendChild(subVideo);
  }
}

function createVideo(mainStream, sub_id) {
  let subVideo = document.createElement('video');
  subVideo.autoplay = true;
  subVideo.muted = true;
  subVideo.srcObject = mainStream;
  subVideo.setAttribute(
    'style',
    'width: 100%; height: 100%; object-fit: contain;object-position: right top;',
  );
  subVideo.setAttribute('playsinline', 'playsinline');
  subVideo.setAttribute('id', 'merged_channel_subview_' + sub_id);
  return subVideo;
}

/// 设定对齐方式
/// [view_id] 传入需要设置的 channel_id
/// [fit_mode] 传入需要设置的对齐方式 [contain|cover|fill|none|scale-down]
async function setTRTCPlatformViewFitMode(view_id, fit_mode) {
  let view = document.getElementById('HTMLID_trtcCloudChannelView' + view_id);
  let video;
  console.log('📘setTRTCPlatformViewFitMode', view_id);
  // 尝试10次 video = view.querySelector("video"); 直到成功
  for (let i = 0; i < 10; i++) {
    video = view.querySelector('video');
    if (video != null) {
      video.setAttribute(
        'style',
        'width: 100%; height: 100%; object-fit: ' +
          fit_mode +
          ';object-position: left top;',
      );
      break;
    } else {
      console.log('📘📘📘📘 未找到 video 重试 ' + i);
      console.log('📘📘📘📘 view_id ' + view_id);
      await new Promise((resolve) => setTimeout(resolve, 200));
    }
  }
}

/// 设定画面拉伸
/// [view_id] 传入需要设置的 channel_id
/// [scale] 传入需要设置拉伸倍率 2 为2倍
async function setTRTCPlatformViewScaleY(view_id, scale) {
  let view = document.getElementById('HTMLID_trtcCloudChannelView' + view_id);
  let video;
  console.log('📘setTRTCPlatformViewScaleY', view_id);
  // 尝试10次 video = view.querySelector("video"); 直到成功
  for (let i = 0; i < 10; i++) {
    video = view.querySelector('video');
    if (video != null) {
      video.style.transform += ' scaleY(' + scale + ')';
      video.style.transformOrigin = 'left bottom';
      break;
    } else {
      console.log('📘📘📘📘 未找到 video 重试 ' + i);
      await new Promise((resolve) => setTimeout(resolve, 200));
    }
  }
}

/// 设定画面拉伸
/// [view_id] 传入需要设置的 channel_id
/// [scale] 传入需要设置拉伸倍率 2 为2倍
async function setTRTCPlatformViewScaleXY(view_id, scaleX, scaleY) {
  let view = document.getElementById('HTMLID_trtcCloudChannelView' + view_id);
  let video;
  console.log('📘setTRTCPlatformViewScaleY', view_id);
  // 尝试10次 video = view.querySelector("video"); 直到成功
  for (let i = 0; i < 10; i++) {
    video = view.querySelector('video');
    if (video != null) {
      video.style.transform += ' scale(' + scaleX + ',' + scaleY + ')';
      video.style.transformOrigin = 'left bottom';
      break;
    } else {
      console.log('📘📘📘📘 未找到 video 重试 ' + i);
      await new Promise((resolve) => setTimeout(resolve, 200));
    }
  }
}

/// 设定画面拉伸与偏移
/// [view_id] 传入需要设置的 channel_id
/// [scaleX] 传入需要设置拉伸倍率 2 为2倍
/// [scaleY] 传入需要设置拉伸倍率 2 为2倍
/// [translateX] 传入需要设置偏移X 百分比
/// [translateY] 传入需要设置偏移Y 百分比
async function setTRTCPlatformViewTransform(
  view_id,
  scaleX,
  scaleY,
  translateX,
  translateY,
) {
  let view = document.getElementById('HTMLID_trtcCloudChannelView' + view_id);
  let video;
  console.log('📘setTRTCPlatformViewTransform', view_id);
  // 尝试10次 video = view.querySelector("video"); 直到成功
  for (let i = 0; i < 10; i++) {
    video = view.querySelector('video');
    if (video != null) {
      video.style.transform += ' scale(' + scaleX + ',' + scaleY + ')';
      video.style.transform +=
        ' translate(' + translateX + '%, ' + translateY + '%)';
      video.style.transformOrigin = 'left bottom';
      break;
    } else {
      console.log('📘📘📘📘 未找到 video 重试 ' + i);
      await new Promise((resolve) => setTimeout(resolve, 200));
    }
  }
}

async function setRemoteViewToFit(view_id) {
  let view = document.getElementById('HTMLID_trtcCloudChannelView' + view_id);
  let video;
  console.log('📘setTRTCPlatformViewFitMode', view_id);
  // 尝试10次 video = view.querySelector("video"); 直到成功
  for (let i = 0; i < 10; i++) {
    video = view.querySelector('video');
    if (video != null) {
      video.setAttribute(
        'style',
        'width: 100%; height: 100%; object-fit: contain;',
      );
      break;
    } else {
      console.log('📘📘📘📘 未找到 video 重试 ' + i);
      await new Promise((resolve) => setTimeout(resolve, 200));
    }
  }
}
