import { durationToSeconds, formatEpisodeTimestamp } from './time'
import type { EpisodeInterface } from './types'

export const hasEnded = (episode: EpisodeInterface) =>
	episode.action &&
	episode.action.action &&
	(episode.action.action.toLowerCase() === 'delete' ||
		(episode.action.position > 0 &&
			episode.action.total > 0 &&
			episode.action.position >= episode.action.total))

export const isListening = (episode: EpisodeInterface) =>
	episode.action &&
	episode.action.action &&
	episode.action.action.toLowerCase() === 'play' &&
	episode.action.position > 0 &&
	!hasEnded(episode)

export const markAs = (episode: EpisodeInterface, read: boolean, url: string) => {
	episode.action = {
		podcast: url,
		episode: episode.url,
		guid: episode.guid,
		action: 'play',
		timestamp: formatEpisodeTimestamp(new Date()),
		started: episode.action?.started || 0,
		position: read ? durationToSeconds(episode.duration || '') : 0,
		total: durationToSeconds(episode.duration || ''),
	}
	return episode
}
