<template>
  <div :id="domId" ref="containerRef" class="ezviz-player-host" />
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
import {
  buildEzvizDomId,
  createEzvizPlayer,
  destroyEzvizPlayer,
  getPlayerMeasureSize,
  getPlayerMeasureTarget,
  resizeEzvizPlayer
} from '../utils/ezvizPlayer.js'

const props = defineProps({
  url: {
    type: String,
    default: ''
  },
  accessToken: {
    type: String,
    default: ''
  },
  playerId: {
    type: [String, Number],
    required: true
  },
  playerConfig: {
    type: Object,
    default: () => ({})
  },
  active: {
    type: Boolean,
    default: true
  }
})

const containerRef = ref(null)
const domId = computed(() => buildEzvizDomId(props.playerId))
let playerInstance = null
let resizeObserver = null

const teardown = async () => {
  if (resizeObserver) {
    resizeObserver.disconnect()
    resizeObserver = null
  }
  await destroyEzvizPlayer(playerInstance)
  playerInstance = null
}

const waitForLayout = async (el) => {
  const measureTarget = getPlayerMeasureTarget(el)
  for (let i = 0; i < 30; i += 1) {
    await new Promise((resolve) => requestAnimationFrame(resolve))
    const { width, height } = getPlayerMeasureSize(el)
    if (width > 0 && height > 0) {
      return measureTarget
    }
  }
  return measureTarget
}

const scheduleResize = (player, containerEl) => {
  const measureTarget = getPlayerMeasureTarget(containerEl)
  const run = () => resizeEzvizPlayer(player, containerEl, props.playerConfig)
  run()
  requestAnimationFrame(run)
  window.setTimeout(run, 200)
  window.setTimeout(run, 600)
  window.setTimeout(run, 1200)
  return measureTarget
}

const setup = async () => {
  await teardown()
  if (!props.active || !props.url || !props.accessToken) {
    return
  }

  await nextTick()
  const containerEl = containerRef.value
  if (!containerEl) {
    return
  }

  await waitForLayout(containerEl)

  try {
    playerInstance = await createEzvizPlayer(containerEl, {
      url: props.url,
      accessToken: props.accessToken,
      playerConfig: props.playerConfig
    })
  } catch (err) {
    console.error('[MonitorLivePlayer] 萤石播放器初始化失败', err)
    return
  }

  if (playerInstance) {
    const measureTarget = scheduleResize(playerInstance, containerEl)
    if (typeof ResizeObserver !== 'undefined') {
      resizeObserver = new ResizeObserver(() => {
        resizeEzvizPlayer(playerInstance, containerEl, props.playerConfig)
      })
      resizeObserver.observe(measureTarget)
    }
  }
}

watch(
  () => [props.url, props.accessToken, props.active, props.playerId],
  setup
)

watch(
  () => props.playerConfig,
  setup,
  { deep: true }
)

onMounted(setup)
onBeforeUnmount(teardown)
</script>

<style scoped>
.ezviz-player-host {
  display: block;
  width: 100%;
  height: 100%;
  max-width: 100%;
  max-height: 100%;
  overflow: hidden;
  background: #0a1418;
}
</style>
