/**
 * Format a date to a timer
 * @param {Date} date The date
 * @return {string}
 */
export const formatTimer = (date) => {
	const minutes = date.getUTCMinutes().toString().padStart(2, 0)
	const seconds = date.getUTCSeconds().toString().padStart(2, 0)
	let timer = `${minutes}:${seconds}`

	if (date.getUTCHours()) {
		timer = `${date.getUTCHours()}:${timer}`
	}

	return timer
}

/**
 * Format a date to a usefull timestamp string for the gPodder API
 * @param {Date} date The date
 * @return {string}
 */
export const formatEpisodeTimestamp = (date) => {
	const year = date.getFullYear()
	const month = (date.getMonth() + 1).toString().padStart(2, '0')
	const day = date.getDate().toString().padStart(2, '0')
	const hours = date.getHours().toString().padStart(2, '0')
	const mins = date.getMinutes().toString().padStart(2, '0')
	const secs = date.getSeconds().toString().padStart(2, '0')

	return `${year}-${month}-${day}T${hours}:${mins}:${secs}`
}

/**
 * Format a date to a localized date string
 * @param {Date} date The date
 * @return {string}
 */
export const formatLocaleDate = (date) => date.toLocaleDateString(undefined, { dateStyle: 'medium' })

/**
 * Returns the number of seconds from a duration feed's entry
 * @param {string} duration The duration feed's entry
 * @return {number}
 */
export const durationToSeconds = (duration) => {
	const splitDuration = duration.split(':').reverse()
	let seconds = parseInt(splitDuration[0])
	seconds += (splitDuration.length > 1) ? parseInt(splitDuration[1]) * 60 : 0
	seconds += (splitDuration.length > 2) ? parseInt(splitDuration[2]) * 60 * 60 : 0
	return seconds
}
