//const HTTP_BASE = "http://localhost:3000";
const HTTP_BASE = "";
const tokens = {};

declare var componentHandler;

function escapeHtml(unsafe) {
  return unsafe
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#039;");
}

function httpGetAsync(token: string, theUrl, callback = null) {
  if (!!token && tokens[token]) {
    clearTimeout(tokens[token]);
    delete tokens[token];
  }
  const t = setTimeout(() => {
    const xmlHttp = new XMLHttpRequest();
    xmlHttp.onreadystatechange = () => {
      if (xmlHttp.readyState === 4 && xmlHttp.status === 200) {
        if (!!callback) {
          callback(xmlHttp.responseText);
        }
      }
    };
    xmlHttp.open("GET", theUrl, true);  // true for asynchronous
    xmlHttp.send(null);
    delete tokens[token];
  }, 500);
  if (!!token) {
    tokens[token] = t;
  }
}




function addProgressBarFunctionality(id: string) {
  const rangediv = document.getElementById(id);
  rangediv.getElementsByClassName("mdl-progress")[0].addEventListener("mdl-componentupgraded", () => {
    let value = parseInt(rangediv.dataset.value, 10);
    setProgress(rangediv, value);
    rangediv.getElementsByClassName("mdl-list__item-secondary-info")[0].innerHTML = `${value}/7`;
    rangediv.getElementsByClassName("minus-arrow")[0].addEventListener("click", () => {
      value = Math.max(1, parseInt(rangediv.dataset.value, 10) - 1);
      setProgress(rangediv, value);
      if (!!rangediv.dataset.dosend) {
        sendCocktail(id, value);
      }
    });
    rangediv.getElementsByClassName("plus-arrow")[0].addEventListener("click", () => {
      value = Math.min(7, parseInt(rangediv.dataset.value, 10) + 1);
      setProgress(rangediv, value);
      if (!!rangediv.dataset.dosend) {
        sendCocktail(id, value);
      }
    });
  });
}

function setProgress(rdiv, v) {
  rdiv.dataset.value = v.toString();
  rdiv.getElementsByClassName("mdl-progress")[0].MaterialProgress.setProgress(100 * (v - 1 ) / 6);
  rdiv.getElementsByClassName("mdl-list__item-secondary-info")[0].innerHTML = `${v}/7`;
}

function sendAge(elem) {
  httpGetAsync("agetoken", `${HTTP_BASE}/update/personal?age=${encodeURI(elem.value)}`);
}

function sendSex(elem) {
  httpGetAsync("sextoken", `${HTTP_BASE}/update/personal?sex=${encodeURI(elem.value)}`);
}

function sendNewCocktail() {
  const cocktail = (document.getElementById("cocktails") as any).value;
  if (cocktail === "") {
    return;
  }
  const level = document.getElementById("pnew").dataset.value;
  httpGetAsync(null, `${HTTP_BASE}/update/newcocktail?cocktail=${encodeURI(cocktail)}&level=${encodeURI(level)}`);
  const elem = document.getElementById(cocktail);
  if (!!elem) {
    setProgress(elem, level);
  } else {
    const list = document.getElementById("cocktaillist");
    let NAME = escapeHtml(cocktail);
    let LEVEL = escapeHtml(level);
    httpGetAsync(null, `${HTTP_BASE}/update/getingredients?cocktail=${encodeURI(cocktail)}`, (data) => {
      document.getElementById(cocktail).parentElement.parentElement.getElementsByClassName("mdl-list__item-sub-title")[0].innerHTML = escapeHtml(data);
    });
    list.innerHTML += (`<li class="mdl-list__item mdl-list__item--two-line"><span class="mdl-list__item-primary-content"><i class="material-icons mdl-list__item-avatar">local_bar</i><span>${NAME}</span><span class="mdl-list__item-sub-title"> </span></span><span class="mdl-list__item-secondary-content">
    <div id="${NAME}" class="mdl-grid" style="width:100px;text-align:center;padding:0;margin:0" data-value="${LEVEL}">
      <div class="mdl-cell" style="width:33.33333333%;margin-right:0px;margin-left:0px"><a class="minus-arrow mdl-list__item-secondary-action" href="#"><i class="material-icons">remove</i></a></div>
      <div class="mdl-cell" style="width:33.33333333%;margin-right:0px;margin-left:0px">
        <div class="mdl-progress mdl-js-progress" style="text-align:center"><span class="mdl-list__item-secondary-info"></span></div>
      </div>
      <div class="mdl-cell" style="width:33.33333333%;margin-right:0px;margin-left:0px"><a class="plus-arrow mdl-list__item-secondary-action" href="#"><i class="material-icons">add</i></a></div>
    </div></span></li>`);
    addProgressBarFunctionality(cocktail);
    componentHandler.upgradeElement(document.getElementById(cocktail).getElementsByClassName("mdl-progress")[0]);
  }
}

function sendCocktail(id, value) {
  const cocktail = id;
  const level = value;
  httpGetAsync("updatetoken" + id, `${HTTP_BASE}/update/newcocktail?cocktail=${encodeURI(cocktail)}&level=${encodeURI(level)}`);
}









function createCookie(name, value) {
  const maxAge = "; max-age=21474836470";
  console.log(name + "=" + value + maxAge + "; path=/");
  document.cookie = name + "=" + value + maxAge + "; path=/";
}

function loadUID(elem) {
  const uid = elem.getElementsByClassName("mdl-textfield__input")[0].value;
  httpGetAsync(null, `${HTTP_BASE}/update/isvaliduid?uid=${encodeURI(uid)}`, (data) => {
    if (data === "valid") {
      console.log("cookie", document.cookie);
      createCookie("uid", uid);
      location.href = "/";
    }
  });
}
