var container = document.querySelector('.container');
var videoTimeline = container.getElementsByClassName('video-timeline')[0];
var progressBar = container.getElementsByClassName('progress-bar')[0];
var volumeBtn = container.getElementsByClassName('volume')[0];
var volumeBtnIcon = volumeBtn.getElementsByTagName('i')[0];
var volumeSlider = container.getElementsByClassName('volume-slider')[0];
var currentVidTime = container.getElementsByClassName('current-time')[0];
var videoDuration = container.getElementsByClassName('video-duration')[0];
var skipBackward = container.getElementsByClassName('skip-backward')[0];
var skipForward = document.getElementsByClassName('skip-forward')[0];
var playPauseBtn = container.getElementsByClassName('play-pause')[0];
var playPauseBtnIcon = playPauseBtn.getElementsByTagName('i')[0];
var timer;
var mainVideo;

function adjustFontSize() {
  var fontSize = (document.body.clientWidth / 600) * 10;
  document.getElementsByTagName('html')[0].style['font-size'] = fontSize + 'px';
}

function hideControls() {
  if (mainVideo.paused) return;
  timer = setTimeout(function () {
    container.classList.remove('show-controls');
  }, 3000);
}

function formatTime(time) {
  var seconds = Math.floor(time % 60);
  var minutes = Math.floor(time / 60) % 60;
  var hours = Math.floor(time / 3600);

  seconds = seconds < 10 ? '0' + seconds : seconds;
  minutes = minutes < 10 ? '0' + minutes : minutes;
  hours = hours < 10 ? '0' + hours : hours;

  if (hours === 0) {
    return minutes + ':' + seconds;
  }
  return hours + ':' + minutes + ':' + seconds;
}

function draggableProgressBar(e) {
  var timelineWidth = videoTimeline.clientWidth;
  progressBar.style.width = e.offsetX + 'px';
  mainVideo.currentTime = (e.offsetX / timelineWidth) * mainVideo.duration;
  currentVidTime.innerText = formatTime(mainVideo.currentTime);
}

function initVideoTimeline() {
  videoTimeline.addEventListener('mousemove', function (e) {
    var timelineWidth = videoTimeline.clientWidth;
    var offsetX = e.offsetX;
    var percent = Math.floor((offsetX / timelineWidth) * mainVideo.duration);
    var progressTime = videoTimeline.querySelector('span');

    if (offsetX < 20) {
      offsetX = 20;
    } else if (offsetX > timelineWidth - 20) {
      offsetX = timelineWidth - 20;
    }
    progressTime.style.left = offsetX + 'px';
    progressTime.innerText = formatTime(percent);
  });
  videoTimeline.addEventListener('click', function (e) {
    var timelineWidth = videoTimeline.clientWidth;
    mainVideo.currentTime = (e.offsetX / timelineWidth) * mainVideo.duration;
  });
}

function initVideoPlayer() {
  mainVideo.addEventListener('timeupdate', function (e) {
    var currentTime = e.target.currentTime;
    var duration = e.target.duration;
    var percent = (currentTime / duration) * 100;
    progressBar.style.width = percent + '%';
    currentVidTime.innerText = formatTime(currentTime);
  });

  mainVideo.addEventListener('loadeddata', function () {
    videoDuration.innerText = formatTime(mainVideo.duration);
  });

  mainVideo.addEventListener('loadedmetadata', function () {
    initVideoTimeline();
    initVideoVolumeButtons();
    initVideoButtons();
  });
}

function initVideoVolumeButtons() {
  volumeBtn.addEventListener('click', function () {
    if (volumeBtnIcon.className === 'fa-volume-xmark') {
      mainVideo.volume = 0.5;
      volumeBtnIcon.className = 'fa-volume-high';
    } else {
      mainVideo.volume = 0.0;
      volumeBtnIcon.className = 'fa-volume-xmark';
    }
    volumeSlider.value = mainVideo.volume * 100;
  });
  volumeSlider.addEventListener('change', function (e) {
    mainVideo.volume = Number(e.target.value) / 100;
    if (e.target.value === 0) {
      volumeBtnIcon.className = 'fa-volume-xmark';
      return;
    }
    volumeBtnIcon.className = 'fa-volume-high';
  });
}

function initVideoButtons() {
  skipBackward.addEventListener('click', function () {
    mainVideo.currentTime -= 5;
  });
  skipForward.addEventListener('click', function () {
    mainVideo.currentTime += 5;
  });
  mainVideo.addEventListener('play', function () {
    playPauseBtnIcon.className = 'fa-pause';
  });
  mainVideo.addEventListener('pause', function () {
    playPauseBtnIcon.className = 'fa-play';
  });
  playPauseBtn.addEventListener('click', function () {
    mainVideo.paused ? mainVideo.play() : mainVideo.pause();
  });
  videoTimeline.addEventListener('mousedown', function () {
    videoTimeline.addEventListener('mousemove', draggableProgressBar);
  });
  document.addEventListener('mouseup', function () {
    videoTimeline.removeEventListener('mousemove', draggableProgressBar);
  });
}

function initVideo() {
  hideControls();
  container.addEventListener('mousemove', function () {
    container.classList.add('show-controls');
    clearTimeout(timer);
    hideControls();
  });

  initVideoPlayer();
}

function getUrlParams() {
  var urlStr = location.search.substring(1);
  var obj = {};
  var paramsArr = urlStr.split('&');
  for (var i = 0, len = paramsArr.length; i < len; i++) {
    var arr = paramsArr[i].split('=');
    obj[arr[0]] = arr[1];
  }
  return obj;
}

function decodeHexStr(str) {
  var i;
  var hexes = str.match(/(\/u.{1,4}|.)/g) || [];
  var back = '';
  for (i = 0; i < hexes.length; i++) {
    var item = hexes[i];
    if (item.length === 6) {
      back += String.fromCharCode(parseInt(hexes[i].substring(2), 16));
    } else {
      back += item;
    }
  }
  return back;
}

(function() {
  adjustFontSize();
  var params = getUrlParams();
  var data = params.data;
  try {
    data = JSON.parse(decodeURIComponent(data));
  } catch (error) {
    data = {};
  }
  var titleDom = document.getElementById('title');
  if (titleDom && data.title) {
    titleDom.innerText = decodeHexStr(data.title)
  }
  var descDom = document.getElementById('desc');
  if (descDom && data.desc) {
    descDom.innerText = decodeHexStr(data.desc)
  }
  mainVideo = document.createElement('video');
  mainVideo.setAttribute('src', data.video);
  mainVideo.setAttribute('poster', data.poster);
  container.appendChild(mainVideo);
  initVideo();
})();
