/**
 *
 * SCOUTING SCRIPTS
 * The Pascack Pi-oneers
 *
 * Author(s): Brian Buckley
 * Contact: larry@team1676.com
 * Last Updated: Jan 9, 2024
 *
 * © FRC Team 1676
 *
 * All rights reserved.
 *
 * -----------------------------
 *
 * HELPER FUNCTIONS
 *  > setLocalStorage
 *  > getLocalStorage
 *  > setCookie
 *  > getCookie
 *  > timeConverter
 *
 * USER SELECT
 *
 * QR GENERATION
 *  > passToQR
 *  > changeQR
 *
 * ONLINE DETECTOR
 *
 */

let version = "x24.2";


/**
 * HELPER FUNCTIONS
 */

function setLocalStorage(key, val) {
  localStorage.setItem(key, val);
}

function getLocalStorage(key) {
  return localStorage.getItem(key);
}

function setCookie(cname, json, exdays) {
  const d = new Date();
  d.setTime(d.getTime() + (exdays*24*60*60*1000));
  let expires = "expires="+ d.toUTCString();
  document.cookie = cname + "=" + JSON.stringify(json) + ";" + expires + ";path=/";
  cookies[cname] = json;

  console.log("`" + cname + "` cookie: ");
  console.log(cookies[cname]);
}

function getCookie(cname) {
  let name = cname + "=";
  let decodedCookie = decodeURIComponent(document.cookie);
  let ca = decodedCookie.split(';');
  for(let i = 0; i <ca.length; i++) {
    let c = ca[i];
    while (c.charAt(0) == ' ') {
      c = c.substring(1);
    }
    if (c.indexOf(name) == 0) {
      return c.substring(name.length, c.length);
    }
  }
  return false;
}

let cookies = {
  "ignore": JSON.parse(getCookie('ignore')),
  "global": JSON.parse(getCookie('global')),
  "match": JSON.parse(getCookie('match')),
  "user": JSON.parse(getCookie('user'))
}

if (cookies['user'].uid > 100) {
  var pImgSrc = $("div.person[data-uid=" + cookies['user'].uid + "] img").attr('src');
  pImgSrc = pImgSrc.split("/");
  $("#profile-img").attr('src', "assets/img/profiles/100/" + pImgSrc[pImgSrc.length - 1]);
}

if (cookies['match'].number > 0) {
  $("#matchNum").val(cookies['match'].number);
  $("#team1").val(cookies['match'].team);
}

function timeConverter(timestamp){
  var a = new Date(timestamp);
  var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
  var year = a.getFullYear();
  var month = months[a.getMonth()];
  var date = a.getDate();
  var hour = a.getHours();
  var min = a.getMinutes();
  var sec = a.getSeconds();
  var milis = a.getMilliseconds();
  var time = month + ' ' + date + ', ' + year + ' ' + hour + ':' + min + ':' + sec; // + ':' + milis;
  return time;
}

function classNameListener(elemId, callback) {
  var elem = document.getElementById(elemId);
  var lastClassName = elem.className;
  window.setInterval( function() {
   var className = elem.className;
    if (className !== lastClassName) {
      callback();
      lastClassName = className;
    }
  },10);
}


/**
 * USER SELECT
 */

$('div.person').each(function () {
  var $this = $(this);
  $this.on("click", function () {
    var img = $(this).children().first().attr('src')
    img = img.split("/");
    $("#profile-img").attr('src', "assets/img/profiles/100/" + img[img.length - 1]);
    setCookie('user', {"uid": $(this).data('uid')}, 1);
    $("#user").modal('hide');
  });
});

function filterPeople(val) {
  $('.nav-link.peep').removeClass('active');
  $('#peepFilter' + val).addClass('active');
  if (val == 0) {
    $('.person').css('display', 'block');
  } else {
    $('.person').css('display', 'none');
    $('.person[data-filter=' + val + ']').css('display', 'block');
  }
}


/**
 * QR CODE
 */

var j = 0;
var cycle;

function generateQR(str) {
  cycle = setInterval(() => {
    passToQR(str);
  }, 200);
}

function passToQR(str) {
  let maxChars = 250;
  var strLen = str.length;
  var qrNum = Math.ceil(strLen / maxChars);
  var data = str.substring(j * maxChars, (j + 1) * maxChars);

  var qrStr = "<<" + (j + 1) + "/" + qrNum + ">>" + data;
  qrStr = qrStr.padEnd(maxChars, '<*>');
  changeQR(qrStr);
  j = (j >= qrNum - 1) ? 0 : j + 1;
}

function changeQR(data) {
  document.getElementById("qrcode").innerHTML = "";

  new QRCode(document.getElementById("qrcode"), {
    text: data,
    width: 264,
    height: 264,
    colorDark : "#000",
    colorLight : "#fff",
    correctLevel : QRCode.CorrectLevel.L
  });
}

function closeQR() {
  clearInterval(cycle);
  document.getElementById("qrcode").innerHTML = "";
  $("#treshy").modal('hide');
}


/**
 * ONLINE DETECTOR
 */

let online = $(".online");
let offline = $(".offline");
let local = $(".local");
let server = $(".server");
let checking = $(".checking");

window.addEventListener('online', () => {
  online[0].style.display = "inline";
  online[1].style.display = "inline";
  offline[0].style.display = "none";
  offline[1].style.display = "none";
});

window.addEventListener('offline', () => {
  online[0].style.display = "none";
  online[1].style.display = "none";
  offline[0].style.display = "inline";
  offline[1].style.display = "inline";
});

addEventListener("load", (event) => {
  if (window.navigator.onLine) {
    online[0].style.display = "inline";
    online[1].style.display = "inline";
  } else {
    offline[0].style.display = "inline";
    offline[1].style.display = "inline";
  }

  if (window.location.hostname == "blark.it") {
    server[0].style.display = "inline";
    server[1].style.display = "inline";
    $("#hist-type").text("online");
  } else {
    local[0].style.display = "inline";
    local[1].style.display = "inline";
    $("#hist-type").text("offline");
  }

  $(".version").text(version);

  checking[0].style.display = "none";
  checking[1].style.display = "none";
});


/**
 * STARS
 */

$("input[name=rating]").click(function() {
  clearInterval(cycle);
  document.getElementById("qrcode").innerHTML = "";
});


/**
 * CLICK FIX
 */

var exited = false;

classNameListener("body", clickFix);

function clickFix() {
  exited = true;
  $("#background").trigger('click');
}