// This is JS solely for the menu page. It
// shouldn't be used by Cap modules.

function initMenu() {
  auth.onAuthStateChanged(function(user) {
    if (user) {
      console.log(`Authenticated user`);
      initUser(user);
    }
    else {
      // direct unauthenticated user to login
      location.pathname = `auth.html`;
    }
  });
}

async function initUser(user) {
  const userDoc = db.collection("users").doc(user.uid);
  let userData = await userDoc.get();

  // Check if the user doc exists. If not then it's a new user so create the doc
  if (!userData.data()) {
    await userDoc.set(userFields(user.email, user.displayName))
    // creates a welcomeEmail document in firestore
    handleWelcomeEmail(user);
  }

  // Perhaps a place for some optimization. Since we set/create the user firestore doc
  // here, we're having to fetch it again in buildMenu().
  // Would be nice if we can pass the doc to build menu.
  // setCapMenuVars(user.uid)
  buildMenu(user);
}

async function buildMenu(user) {
  // TODO: see about passing userDoc/Data as an arg here
  const userDoc = db.collection("users").doc(user.uid);
  let userData = await userDoc.get();

  displayGreeting(`${user.displayName} (${user.email})`);
  displayAnswersLink(userData.data());
  displayCsvButtons(userData.data());
  displayCards(userData.data());
}

function displayGreeting(displayName) {
  const greeting = document.getElementById("greeting");
  greeting.textContent = `Welcome ${displayName}`;
}

function displayAnswersLink(userData) {
  if(isPretestComplete(userData)) {
    const menuItems = document.getElementsByClassName('review-answers');
    const answersLink = `<a href='/review-answers.html'>My Results</a>`;

    for (let i = 0; i < menuItems.length; i++) {
      menuItems[i].innerHTML = answersLink;
    }
  }
}

function displayCsvButtons(userData) {
  if (!userData.isAdmin) { return; }

  const csvButtonsRow = document.getElementById("csv-buttons-row");
  const prePostButton = `
    <button id="pre-post-csv" class="uk-button uk-button-secondary">Pre/Post CSV</button>
    <div uk-dropdown>
      <ul class='uk-nav uk-dropdown-nav'>
        <li data-version='1.0' onclick='exportCsv(this);'>v1.0 Data</li>
        <li class='uk-nav-divider'></li>
        <li data-version='2.0' onclick='exportCsv(this);'>v2.0 Data</li>
      </ul>
    </div>
  `;

  csvButtonsRow.innerHTML = prePostButton
}

function displayCards(userData) {
  const preStatus = isPretestComplete(userData);
  const postStatus = isPosttestComplete(userData);

  setPretestState(preStatus, "pretest-module");
  setPosttestState(preStatus, postStatus, "posttest-module");
}

function isPretestComplete(userData) {
  return userData.PreAacademyComplete == 1;
}

function isPosttestComplete(userData) {
  return userData.PostAacademyComplete == 1;
}

function setPretestState(complete, cardId) {
  // Inital state of Pretest card is disabled to prevent user click prior to
  // user doc creation. `complete` var here is proof user doc exists.

  // Card is enabled when complete is false
  // Card is disabled and badge added when complete is true
  const card = document.getElementById(cardId);

  // card.classList.add("disabled");
  if (!complete) {
    card.classList.remove('disabled');
    return;
  }

  addBadge(cardId);
}

function setPosttestState(preComplete, postComplete, cardId) {
  // Disabled when not live
  // Disabled until pretest completed
  // Badge added when completed
  // Disabled when completed
  const card = document.getElementById(cardId);
  const isLive = card.dataset.live;

  if (isLive == "false") {
    const info = document.getElementById("posttest-info");

    info.innerHTML = `
      Coming Soon!<br />Available &lt; some date &gt;
    `

    card.classList.add("disabled");
    return;
  }

  if (preComplete && !postComplete) {
    card.classList.remove("disabled");
  }

  if (postComplete) { addBadge(cardId); }
}

function addBadge(cardId) {
  const badge = document.querySelector(`#${cardId} .uk-card-badge`);
  badge.classList.remove("hidden");
}
