<script setup lang="ts">
import Artplayer from "artplayer";
import Hls from "hls.js";

interface Props {
    src: string;
    id: string;
}

const props = withDefaults(defineProps<Props>(), {
});

const emit = defineEmits(['get-instance'])

const options = computed(() => {
    console.log(props.src)
    return {
        url: props.src || '',
        type: 'm3u8',
        customType: {
            m3u8: playM3u8,
        },
        autoSize: true,
        autoMini: true,
        playbackRate: true,
        fullscreen: true,
        aspectRatio: true,
        setting: true,
        lock: true,
        autoOrientation: true,
        autoPlayback: true,
        id: props.id,
    }
})
const artplayerRef = ref();
const instance = ref();

function playM3u8(video: HTMLMediaElement, url: string, art: Artplayer) {
    if (Hls.isSupported()) {
        if (art.hls) art.hls.destroy();
        const hls = new Hls();
        hls.loadSource(url);
        hls.attachMedia(video);
        art.hls = hls;
        art.on('destroy', () => hls.destroy());
    } else if (video.canPlayType('application/vnd.apple.mpegurl')) {
        video.src = url;
    } else {
        art.notice.show = 'Unsupported playback format: m3u8';
    }
}

onMounted(() => {
    instance.value = new Artplayer({
        container: artplayerRef.value,
        ...options.value,
    })
    nextTick(() => {
        emit('get-instance')
    })
})

onBeforeUnmount(() => {
    if (instance.value && instance.value.destroy) {
        instance.value.destroy(false)
    }
})
</script>

<template>
    <div class="flex items-center justify-center">
        <div class="w-1/2 aspect-video" ref="artplayerRef"></div>
    </div>
    <div class="h-lvh">
        test
        test
        ste
        t

        t

        t
    </div>
    <div class="h-lvh">
    </div>
</template>
