<template>
  <slot 
    :currentPlayItemIndex="currentPlayItemIndex" 
    :currentPlayItemId="currentPlayItemId"
    :isPlaying="audioPlayer.isPlaying.value"
  />
</template>

<script setup lang="ts">
import { ref, watch } from 'vue'
import { useSimpleListAudioPlayer } from '../composeabe/SimpleAudioPlayer';
import { RandomUtils } from '@imengyu/imengyu-utils';

const props = defineProps<{
  list: { 
    id: number,
    title: string,
    src: string,
  }[],
  playMode: 'loop'|'random'|'list',
  playAuto: boolean,
}>();

let lock = false;
const currentPlayItemIndex = ref(0);
const currentPlayItemId = ref(0);
const audioPlayer = useSimpleListAudioPlayer(async () => props.list, false, () => {
  if (lock)
    return;
  lock = true;
  setTimeout(() => {
    if (props.playAuto === true) {
      switch (props.playMode) {
        case 'loop': audioPlayer.restart(); break;
        case 'random': playItem(props.list[RandomUtils.genRandom(0, props.list.length - 1)].id); break;
        case 'list': 
          if (currentPlayItemIndex.value < props.list.length - 1)
            playItem(props.list[currentPlayItemIndex.value + 1].id); 
          else
            currentPlayItemId.value = 0;
          break;
      }
    }
    lock = false;
  }, 100);
});

function playItem(id: number) {
  currentPlayItemIndex.value = props.list.findIndex((item) => item.id == id);
  currentPlayItemId.value = id;
  const item = props.list[currentPlayItemIndex.value];
  if (item) {
    audioPlayer.load(item.src);
    audioPlayer.play();
  }
}

watch(() => props.list, () => {
  audioPlayer.reloadList();
});

defineExpose({
  playFirst() {
    if (props.list.length > 0)
      playItem(props.list[0].id)
  },
  playpause(id: number) {
    if (id == currentPlayItemId.value) {
      if (audioPlayer.isEnded.value) 
        audioPlayer.restart();
      else
        audioPlayer.playpause();
    }
    else {
      playItem(id);
    }
  },
  pause() {
    audioPlayer.pause();
  },
})
</script>