import {parseText} from 'media-captions';
import Fetch from "@11ty/eleventy-fetch";
import path from 'path';

class SearchIndex {
  data() {
    return {eleventyExcludeFromCollections:["episode"], layout: null}
  }

  async render (data) {
    const episodesWithTranscript = data.collections.episode.filter(e=>e.data.podcast?.transcriptUrl)
    const promises = episodesWithTranscript.map((episode)=>{
      const {transcriptUrl} = episode.data.podcast
      return Fetch(transcriptUrl, {type:'text', duration: "1d"})
      .then(srt_buffer=>parseText(srt_buffer.toString(), {type:'srt'}))
      .then(({cues})=>cues)
      .then((cues)=>({
        name: path.basename(transcriptUrl,".srt"), 
        episode: episode.data.episode,
        season: episode.data.season,
        title: episode.data.title,
        url: `${this.url(episode.url)}`,
        cues: cues.map(({id, startTime, text})=>({id,startTime,text}))
      }))
      })
    const result = await Promise.all(promises)
    return JSON.stringify(result)
  }
}

export default SearchIndex