// ==UserScript==
// @name        tiktok
// @description
// @version     1
// @match       *://*.tiktok.com/*
// @grant       GM_setClipboard
// ==/UserScript==

(function () {
	'use strict';
	var css_view_count = 'strong.video-count[data-e2e="video-views"]',
//	css_item = 'div.video-feed-item',
//	css_link = 'a.video-feed-item-wrapper[href*="/video/"]',
	css_item = 'div[class*="-DivItemContainer"]',
	css_link = 'div[class*="-DivWrapper"] > a[href*="/video/"]',
	css_close = 'button[class*="-ButtonBasicButtonContainer-StyledCloseIconContainer"]',
	css_scroll_left = 'button[class*="-ButtonBasicButtonContainer-StyledVideoSwitchV2"][data-e2e="arrow-left"]',
	css_scroll_right = 'button[class*="-ButtonBasicButtonContainer-StyledVideoSwitchV2"][data-e2e="arrow-right"]';
	document.addEventListener('wheel', function (e) {
		if (window.location.href.includes('/video/') && document.querySelector('video:hover')) {
			e.preventDefault();
			document.querySelector(e.deltaY < 0 ? css_scroll_left : css_scroll_right).click();
		}
	}, {passive: false});
	document.addEventListener('keydown', function (e) {
		switch(e.key) {
			case 'Escape': {
				if (window.location.href.includes('/video/')) {
					e.preventDefault();
					document.querySelector(css_close).click();
				}
				break;
			}
			case 'Insert': {
				e.preventDefault();
				var item = hover_item();
				if (item) GM_setClipboard(item_url(item));
				break;
			}
			case 'Delete': {
				if (!e.shiftKey) break;
				e.preventDefault();
				video_items().filter(item => !item.querySelector('svg.private')).forEach(item => item.remove());
				break;
			}
			case 'PageUp':
			case 'PageDown': {
				if (!e.shiftKey) break;
				e.preventDefault();
				var items = video_items(),
				sort_type = e.key === 'PageDown',
				sort_cmp = (a, b) => a === b ? 0 : ((sort_type ? a > b : a < b) ? 1 : -1),
				view_count = function (item) {
					var view_text = item.querySelector(css_view_count);
					if (!view_text) return 0;
					var view_count = view_text.innerText,
					view_mult = 1;
					if (view_count.substr(-1) === 'K') {
						view_count.slice(0,-1);
						view_mult = 1000;
					} else if (view_count.substr(-1) === 'M') {
						view_count.slice(0,-1);
						view_mult = 1000000;
					}
//					console.log([view_text,view_count,view_mult,parseFloat(view_count)*view_mult]);
					return parseFloat(view_count)*view_mult;
				};
				items.sort((a, b) => sort_cmp(view_count(a), view_count(b)));
				items.forEach(item => item.parentNode.appendChild(item));
				break;
			}
			case '`': {
				e.preventDefault();
				var out = [],
				urls = video_urls(),
				urls_count = urls.length,
				urls_count_str = urls_count;
				if (unsafeWindow.hasOwnProperty('__NEXT_DATA__')) {
					try { // user page
						out.push('sec_uid=' + unsafeWindow.__NEXT_DATA__.props.pageProps.userInfo.user.secUid);
						out.push('uid=' + unsafeWindow.__NEXT_DATA__.props.pageProps.userInfo.user.id);
						out.push('unique_id=' + unsafeWindow.__NEXT_DATA__.props.pageProps.userInfo.user.uniqueId);
						urls_count_str += '/' + unsafeWindow.__NEXT_DATA__.props.pageProps.userInfo.stats.videoCount;
					} catch {
						try { // audio page
							out.push('music_id=' + unsafeWindow.__NEXT_DATA__.props.pageProps.musicInfo.music.id);
							urls_count_str += '/' + unsafeWindow.__NEXT_DATA__.props.pageProps.musicInfo.stats.videoCount;
						} catch {
							try { // tag page
								out.push('challenge_id=' + unsafeWindow.__NEXT_DATA__.props.pageProps.challengeInfo.challenge.id);
								urls_count_str += '/' + unsafeWindow.__NEXT_DATA__.props.pageProps.challengeInfo.stats.videoCount;
							} catch {}
						}
					}
				} else if (unsafeWindow.hasOwnProperty('SIGI_STATE')) {
					try { // user page
						out.push('sec_uid=' + unsafeWindow.SIGI_STATE.UserModule.users[unsafeWindow.SIGI_STATE.UserPage.uniqueId].secUid);
						out.push('uid=' + unsafeWindow.SIGI_STATE.UserModule.users[unsafeWindow.SIGI_STATE.UserPage.uniqueId].id);
						out.push('unique_id=' + unsafeWindow.SIGI_STATE.UserModule.users[unsafeWindow.SIGI_STATE.UserPage.uniqueId].uniqueId);
						urls_count_str += '/' + unsafeWindow.SIGI_STATE.UserModule.stats[unsafeWindow.SIGI_STATE.UserPage.uniqueId].videoCount;
					} catch {
						try { // audio page
							out.push('music_id=' + unsafeWindow.SIGI_STATE.MusicModule.musicInfo.music.id);
							urls_count_str += '/' + unsafeWindow.SIGI_STATE.MusicModule.musicInfo.stats.videoCount;
						} catch {
							try { // tag page
								out.push('challenge_id=' + unsafeWindow.SIGI_STATE.ChallengePage.challengeInfo.challenge.id);
								urls_count_str += '/' + unsafeWindow.SIGI_STATE.ChallengePage.challengeInfo.stats.videoCount;
							} catch {}
						}
					}
				}
				out.push(urls_count_str);
				if (confirm(out.join('\n')) && urls.length) {
					var urls_str = urls.join('\n');
					console.log(urls_str);
					GM_setClipboard(urls_str);
				}
				break;
			}
			default: return;
		}
	});
	function hover_item() {
		var item = document.querySelector(css_item + ':hover');
		if (item && item.querySelector(css_link)) return item;
		return false;
	}
	function video_items() {
		return Array.from(document.querySelectorAll(css_item)).filter(item => item.querySelector(css_link));
	}
	function video_urls() {
		return Array.from(document.querySelectorAll(css_item + ' ' + css_link)).map(link => link.href);
	}
	function item_url(item) {
		return item.querySelector(css_link).href;
	}
})();