<%- include('./partials/header'); %>

<link rel="stylesheet" href="https://vjs.zencdn.net/7.10.2/video-js.css">
<link rel="stylesheet" href="/assets/css/streamer.css">

<script src="https://vjs.zencdn.net/7.10.2/video.min.js"></script>
<script type="application/javascript" src="/assets/js/tooltipjs/tooltip.js"></script>

<div id="streamer-error" class="alert alert-danger alert-dismissible fade show" role="alert">
	<span id="streamer-error-message"></span>
</div>
<div id="streamer-success" class="alert alert-success alert-dismissible fade show" role="alert">
	<span id="streamer-success-message"></span>
</div>
<div class="stream-overlay">
	<div class="stream-popout">
		<video loop id="live-stream" class="video-js vjs-16-9 vjs-big-play-centered" controls preload="auto" autoplay="true"
			fluid="true" width="1280" height="720" poster="/assets/img/thumbnail.png">
			<p class="vjs-no-js">
				To view this video please enable JavaScript, and consider upgrading to a
				web browser that
				<a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a>
			</p>
		</video>

		<!-- Mobile tabs -->
		<ul class="mobile-tabs nav nav-tabs" role="tablist">
			<li class="nav-item">
				<a class="nav-link active" id="chat-tab" data-toggle="tab" role="tab" href="" aria-selected="true">Chat</a>
			</li>
			<li class="nav-item">
				<a class="nav-link" id="about-tab" data-toggle="tab" role="tab"  href="" aria-selected="false">About</a>
			</li>
		</ul>

		<!-- Mobile interaction buttons -->
		<div class="interaction-btns mobile-active">
			<button type="submit" class="btn btn-sm btn-primary follow-streamer-btn">Follow</button>
			<button type="submit" class="btn btn-sm btn-success donate-btn">Donate</button>
			<button type="submit" class="btn btn-sm btn-danger report-btn"><i class="icofont icofont-flag"></i></button>
		</div>

		<div class="info-box">
			<div class="profile-picture"><img src="/assets/img/defaultpfp.png" id="avatar" class="circle-crop" alt="Avatar"></div>
			<div class="streamer-content mb-3">
				<span class="stream-title desktop-active lead"></span>
				<!-- <span id="stream-title" class="lead" title="Title" data-tooltip="{ 'offset': 10, 'class': 'title-tooltip' }"></span>
					<script type="application/javascript">tooltip.setOptions({tooltipId: "title-tooltip", offsetDefault: 20});</script> -->


				<div class="streamer-name">
					<img src="/assets/img/chat/badges/staff.png" id="staffbadge" width="15" height="15"	alt="[Throwdown Staff]" visible="false" title="ThrowdownTV Staff">
					<img src="/assets/img/chat/badges/vip.png" id="vipbadge" width="15" height="15" alt="[VIP]"	title="ThrowdownTV VIP Member">
					<span id="stream-display-name" class="lead"></span>
				</div>
			</div>

			<div class="streamer-buttons">
				<div class="streamer-button-content">
					<span id="live-status">LOADING...</span>
					<span class="viewers text-danger" title="Live Viewers">
						<i class="streamer-icon icofont icofont-eye-alt"></i><span class="viewer-count">0</span>
					</span>
					<span class="followers text-primary" title="Followers">
						<i class="streamer-icon icofont icofont-people"></i><span class="follow-count">0</span>
					</span>
					<div class="interaction-btns desktop-active">
						<button type="submit" class="btn btn-sm btn-primary follow-streamer-btn">Follow</button>
						<button type="submit" class="btn btn-sm btn-success donate-btn">Donate</button>
						<button type="submit" class="btn btn-sm btn-danger report-btn"><i class="icofont icofont-flag"></i></button>
					</div>
				</div>
			</div>
		</div>

		<span class="stream-title mobile-active lead"></span>
		<div id="stream-description"></div>
	</div>
	<iframe class="chat-popout" frameborder="0" height="720px"></iframe>
</div>

<!-- Mobile layout support -->
<script type="application/javascript">
	//Initialize the visibility of the stream metadata and chat and listen for further resizes
	initVisibility();
	$(window).resize(() => {initVisibility()});

	//Chat tab handling
	$(`#chat-tab`).on(`click`, e => {
		//Show the chat and hide the stream metadata
		$(`.chat-popout`).show();
		$(`#stream-description`).hide();
	});

	//About tab handling
	$(`#about-tab`).on(`click`, e => {
		//Hide the chat and show the stream metadata
		$(`.chat-popout`).hide();
		$(`#stream-description`).show();
	});

	/** 
	 * Shows and hides the chat and stream metadata depending 
	 * on the value of the tab selections. Called on resize of 
	 * the window. 
	 */
	function initVisibility(){
		//Check if the tabs are available for clicking
		if($(`.mobile-tabs`).is(`:visible`)){ 
			//Get the selected aria status for the chat tab and parse to a boolean
			let chatSelected = $(`#chat-tab`).attr(`aria-selected`) === "true" ? true : false;

			//Show the chat and hide the stream metadata if selected and vice versa
			if(chatSelected){
				$(`.chat-popout`).show();
				$(`#stream-description`).hide();
			}
			else {
				$(`.chat-popout`).hide();
				$(`#stream-description`).show();
			}
		}
		else {
			//Show all
			$(`.chat-popout`).show();
			$(`#stream-description`).show();
		}
	}
</script>

<script type="application/javascript">
	const streamer = window.location.pathname.split(`/`)[1].toLowerCase();

	$(document).ready(() => {
		// Player
		let player = videojs(`live-stream`, {
			controls: true,
			autoplay: true,
			preload: `auto`,
			errorDisplay: false
		});

		let live = false;

		// Intially Hide Badges
		$(`#staffbadge`).hide();
		$(`#vipbadge`).hide();

		$(`#follow-btn-form`).attr(`action`, `/follow/${streamer}`);
		$(`.report-btn`).attr(`href`, `/report/${streamer}`);
		$(`#streamer-error`).hide();
		$(`#streamer-success`).hide();

		fetch(`/authenticated`).then(data => data.json()).then(userdata => {
			const username = userdata.username;

			$(`.chat-popout`).attr(`src`, `/chat/${streamer}`);

			$(`#follow-btn-form`).attr(`action`, `/follow/${streamer}`);
			$(`.follow-streamer-btn`).attr(`title`, `Follow ${streamer}`);
			$(`.donate-btn`).attr(`title`, `Donate to ${streamer}`);
			$(`.report-btn`).attr(`title`, `Report ${streamer} for a TOS violation`);

			const getStreamData = () => {
				fetch(`/api/public-stream-data/${streamer}`).then(data => data.json()).then(data => {
					$(`#stream-display-name`).text(data.displayName);
					$(`.stream-title`).text(data.streamTitle);
					//$(`.stream-title`).attr(`title`, `${data.streamTitle}`);
					//$(`#title-tooltip`).text(`${data.streamTitle}`); //Tooltip
					$(`#stream-description`).html(data.streamDescription);
					//$(`.donate-btn`).attr(`action`, `${data.donationLink}`);
					$.get(data.avatarURL).then(successCallback, errorCallback);
					$(`.follow-count`).text(data.followers.length);

					function successCallback(response) {
						$(`#avatar`).attr(`src`, `${data.avatarURL}`);
					}

					function errorCallback(error) {
						$(`#avatar`).attr(`src`, `/assets/img/defaultpfp.png`);
					}

					// Check to see if the user is a VIP or a staff member
					let streamerVIP = data.isVip;
					let streamerStaff = data.isStaff;
					if(streamerVIP) {
						$(`#vipbadge`).show();
					}
					if(streamerStaff) {
						$(`#staffbadge`).show();
						$(`#vipbadge`).hide();
					}

					if(streamer === userdata.username) {
						$(`.follow-streamer-btn`).attr(`disabled`, true);
						$(`.report-btn`).attr(`disabled`, true);

						$(`.follow-streamer-btn`).attr(`title`, `You cannot follow yourself.`);
						$(`.report-btn`).attr(`title`, `You cannot report yourself.`);
					}
					if(data.followers.includes(userdata.username)) {
						$(`.follow-streamer-btn`).html(`Unfollow`);
						$(`.follow-streamer-btn`).attr(`action`, `/unfollow/${streamer}`);
						$(`.follow-streamer-btn`).attr(`title`, `Unfollow ${streamer}`);
					}
					$(`.donate-btn`).on(`click`, e => {
						window.open(data.donationLink);
					});
					$(`.report-btn`).on(`click`, e => {
						window.open(`/report/${streamer}`);
					});
				});
			}

			const checkCrucialData = () => {
				fetch(`/api/public-stream-data/${streamer}`).then(data => data.json()).then(data => {
					$(`.viewer-count`).text(data.viewers.length);
					if(data.isSuspended) return window.location.reload();
					if(data.isLive === true){
						if(live === false){
                            live = true;
							setTimeout(() => {
								player.src({
									src: `https://video-${data.rtmpServer}.throwdown.tv/live/${streamer}/index.m3u8`,
									type: `application/x-mpegURL`,
								})
								$(`#live-status`).text(`LIVE`);
								$(`#live-status`).removeClass(`offline`).addClass(`online`);
							}, 6000)
						}
					} 
					else {
						$(`#live-status`).text(`OFFLINE`);
						$(`#live-status`).removeClass(`online`).addClass(`offline`);
						if(live === true){
							player.src({
								src: `/offline`,
								type: `application/x-mpegURL`,
							});
							live = false;
						}
					}
				});
			}

			player.controlBar.progressControl.seekBar.hide();

			setInterval(getStreamData, 5e3);
			setInterval(checkCrucialData, 5000);
            checkCrucialData();
			getStreamData();

			$(`.follow-streamer-btn`).on(`click`, e => {
				let postUrl = `/follow/${streamer}`;

				if ($(`.follow-streamer-btn`).html() === `Unfollow`) {
					postUrl = `/unfollow/${streamer}`;
					$(`#follow-btn-form`).attr(`action`, `/unfollow/${streamer}`);
				}

				$.ajax({
					type: `post`,
					url: `${postUrl}`,
					data: $(`.follow-streamer-btn`).serialize()
				}).then(res => {
					if (res.errors) {
						$(`#streamer-error`).show();
						$(`#streamer-error-message`).text(res.errors);
					} else if (res.success) {
						$(`#streamer-success`).show();
						$(`#streamer-success-message`).text(res.success);
						fetch(`/api/public-stream-data/${streamer}`).then(data => data.json()).then(data => {
							if (data.followers.includes(userdata.username)) {
								$(`.follow-streamer-btn`).html(`Unfollow`);
								$(`.follow-streamer-btn`).attr(`action`,
									`/unfollow/${streamer}`);
								$(`.follow-streamer-btn`).attr(`title`,
									`Unfollow ${streamer}`);
							} else {
								$(`.follow-streamer-btn`).html(`Follow`);
								$(`.follow-streamer-btn`).attr(`action`,
									`/follow/${streamer}`);
								$(`.follow-streamer-btn`).attr(`title`,
									`Follow ${streamer}`);
							}
						})
					}
					setTimeout(function(){ $(`#streamer-success`).hide(); }, 2000);
				});
			});

			player.on(`error`, event => {
				$(`#live-status`).text(`LOADING...`);
				$(`#live-status`).removeClass(`offline`).removeClass(`online`);
                live = false;
				setTimeout(() => {
					player.src({
                        src: `https://video-${data.rtmpServer}.throwdown.tv/live/${streamer}/index.m3u8`,
                        type: `application/x-mpegURL`,
                    })
                    live = true;
				}, 6000)
			});
		});
	});
</script>
