import {ref, watch} from 'vue'
import {createEventHook} from "@vueuse/core";
import {getVideoPlayInfo} from "@/api/webApi/webVideo";

export const useVideoPlay = function (videoProps) {
    const safeUrl = ref('')
    const coverUrl = ref('')
    const srcChange = createEventHook()

    const isPlayUrl = (src) => src?.toLowerCase().startsWith('http')

    watch([() => videoProps.src, () => videoProps.aliIdType], (n, o) => {
        // TODO: 目前还没有测试切换播放源的问题，以观后效。
        const oldVal = {src: o[0], aliIdType: o[1]}
        const newVal = {src: n[0], aliIdType: n[1]}

        if (isPlayUrl(newVal.src)) {
            safeUrl.value = newVal.src
            srcChange.trigger(newVal, oldVal).then()
        } else if (newVal.src) {
            // 假定这里的src就是aliId
            getVideoPlayInfo({videoId: newVal.src}).then(res => {
                const {palyUrl: play, coverUrl: cover} = res.data
                if (isPlayUrl(play)) {
                    safeUrl.value = play
                    coverUrl.value = cover
                    srcChange.trigger(newVal, oldVal).then()
                }
            })
        }
    }, {immediate: true})

    return {
        safeUrl,
        coverUrl,
        onSrcChange: srcChange.on
    }
}