function getSelectedTweetIds () {
	var tweetIds = Array.from(document.querySelectorAll("*[name='select_tweet']")).filter(cb => cb.checked).map(cb => cb.value)
	
	return tweetIds
}

function selectAllTweets (isSelected) {
	if (isSelected == undefined) {
		isSelected = true;
	}
	
	var tweetSelectionEls = Array.from(document.querySelectorAll("*[name='select_tweet']"));
	
	tweetSelectionEls.forEach(tsEl => tsEl.checked = isSelected)
}

function swapVideoPlayer(imgEl, videoUrl, videoType) {
  
  if (videoType == 'video/youtube' || videoType == 'video/bitchute') {
    
	if (videoType == 'video/youtube') {
		videoUrl += '?enablejsapi=1&widgetid=1&modestbranding=1&playsinline=true&showinfo=0&autoplay=1&rel=0&mute=0';
	} else if (videoType == 'video/bitchute') {
		videoUrl += '?autoplay=1';
	}
	
    var iframe = document.createElement('iframe');
	iframe.src = videoUrl;
  iframe.height = imgEl.height;
  iframe.width = imgEl.width;	
  iframe.setAttribute('allowfullscreen','allowfullscreen');
  iframe.setAttribute('allow', 'autoplay');
    iframe.style.border = '0';
	imgEl.replaceWith(iframe);
	
	
	

	
    return iframe;
  }
  
  var vid = document.createElement('video');
  var src = document.createElement('source');
  vid.appendChild(src);

  vid.poster = imgEl.src;
  vid.controls = "controls";
  vid.height = imgEl.height;
  vid.width = imgEl.width;
  vid.playsInline = true;
  vid.autoplay = true;
    
  src.src = videoUrl;
  src.type = videoType;

  imgEl.replaceWith(vid);
  return vid;
}

function noteCardFormat (tweet, annotation) {
	if (!tweet) { return ""; }
	if (!annotation) { annotation = ''; } else { annotation = '\n' + annotation + '\n'; }
	
	var now = new Date();
	
	var s = `---

${formatTime(now)}
${annotation}
${extendedFormat(tweet)}

`;

	return s;
}


function simpleFormat (tweet) {
	if (!tweet) { return ""; }

	var s;
	with (tweet) {
		if( !tweet['source_url'] ) { source_url = null; }
		
		s = 
`${source_url || ''}

${display_name}
@${handle}
${created_at}

${text || '(no text)'}
`;
	}
	return s.trim();
}

function htmlToText(html) {
    var temp = document.createElement('div');
    temp.innerHTML = html;
    return temp.textContent; // Or return temp.innerText if you need to return only visible text. It's slower.
}

function extendedFormat (tweet) {
	if (!tweet) { return ""; }
	
	var s;
	
	if (!tweet.text && tweet.html) {
		// FIXME: HTML to text
		tweet.text = htmlToText(tweet.html.replaceAll('</p>', '</p>\n\n'));
	}
	
	with (tweet) {
		var total_rt_count = (public_metrics.quote_count || 0) + (public_metrics.retweet_count || 0);
		
		s = 
`${source_url || ''}

${display_name}
@${handle}
${created_at}
${!isNaN(public_metrics.reply_count) ? public_metrics.reply_count : 'unknown'} replies, ${total_rt_count} rts, ${public_metrics.like_count} likes
${tweet['retweeted_by'] ? 'Retweeted by ' : tweet['retweeted_by']}

${text || '(no text)'}

${tweet['card'] ? "Card:\n" + cardFormat(card) : ''}

${tweet['quoted_tweet'] ? "Quoted Tweet:\n" + simpleFormat(quoted_tweet) : ''}
`;
	}
	return s.trim();
}


function cardFormat (card) {
	if (!card) { return ""; }
	
	var s;
	with (card) {
		s = 
`${source_url || ''}

${display_url}
${title}
${content}
`;
	}
	return s;
}

function jsonFormat (tweet) {
	return JSON.stringify(tweet, null, 2);
}


function formatDate (date) {
	return date.getFullYear() 
		+ "-" + (date.getMonth() + 1).toString().padStart(2, '0')
		+ "-" + date.getDate().toString().padStart(2, '0');
}

function formatTime (date) {
	return ("" + date.getHours()).padStart(2, "0")
		+ ":" + ("" + date.getMinutes()).padStart(2, "0")
		+ ":" + ("" + date.getSeconds()).padStart(2, "0")
}

function copyToClipboard (text) {
	navigator.clipboard.writeText(text);
}

function tweetById (tweetId) {
	var tweets = window.dataset.get().filter(t => t.feed_item.id == tweetId);
	
	if (!tweets.length) {
		return null;
	}
	
	return tweets[0].feed_item;
}


function copyTweetToClipboard (tweetId) {
	var text = noteCardFormat(tweetById(tweetId));
	return copyToClipboard(text)
}

async function swipeTweetToNotesApp (tweetId) {
	const { value: annotation } = await Swal.fire({
	  input: 'textarea',
	  inputLabel: 'Add annotation to swipe?',
	  inputPlaceholder: 'Type your annotation here...',
	  inputAttributes: {
		'aria-label': 'Type your annotation here'
	  },
	  showCancelButton: true,
	  cancelButtonText: 'No annotation'
	})
	
	var noteId = formatDate(new Date()) + '-swipe.md'
	var url = notesAppUrl + '/intent/prepend-text/' + noteId
	var text = noteCardFormat(tweetById(tweetId), annotation);
	
	
	
	
	var params = new URLSearchParams({
		text: text,
		should_create: 1
	});
	
	return fetch(url + '?' + params).then(function (r) {
		Toast.fire({
		  icon: 'success',
		  title: 'Tweet swiped.'
		});
	
		return r;
	});
}