// listen for Captivate to tell us it's loaded and ready
function init(capModule) {
  auth.onAuthStateChanged(function(user) {
    if (user) {
      console.log(`Authenticated user`)
      initModule(user, capModule)
    }
    else {
      // direct unauthenticated user to login
      console.log("UN-authenticated user ... ")
      location.pathname = `auth.html`
      alert("You need to sign in to continue")
    }
  });
}

function initModule(user, capModule) {
  // initGTM(user);
  // evt.Data carries the interface object.
  // It is same as window.cpAPIInterface
  // console.log(interface.getEventEmitter())
  // const eventEmitterObj = interface.getEventEmitter();

  const userDoc = db.collection("users").doc(user.uid);
  const interface = window.cpAPIInterface;

  initSharedVariables(user, userDoc, interface);
  initLastSlideVisited(user, userDoc, interface, capModule);
}

function initGTM(user) {
  // window.dataLayer = window.dataLayer || [];

  // if (window.dataLayer.push({ 'userId' : user.uid })) {
  //   // Google Tag Manager
  //   (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
  //   new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
  //   j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
  //   'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
  //   })(window,document,'script','dataLayer','GTM-KK9P42Z');
  //   // End Google Tag Manager
  // }
}

function initSharedVariables(user, userDoc, interface) {
  const dataSet = COURSE_DATA

  userDoc.get().then(doc => {
    // retrieve from firestore and set through CP's API
    Object.keys(dataSet).forEach(varName => {
      value = doc.data()[varName]

      if (value === undefined) { return; }

      interface.setVariableValue(varName, value);
      console.log(`CP variable '${varName}' set to ${value}`);
      initVariableChangeListener(user, varName, interface)
    })
  }).catch(function(error) {
    console.log(`Error setting CP variable and/or change listener`, error);
    // add the listener anyways? need to pass varName then somehow below.
    // initVariableChangeListener(user, varName, interface)
  });
}

function initVariableChangeListener(user, varName, interface) {
  cpAPIEventEmitter.addEventListener(
    "CPAPI_VARIABLEVALUECHANGED",
    function() {
      updateVariable(
        "users",
        user.uid,
        varName,
        interface.getVariableValue(varName)
      )},
    varName
  );
  console.log(`Event listener registered for variable '${varName}'`)
}

function updateVariable(collection, docId, varName, newValue) {
  db.collection(collection).doc(docId).set({
    [varName]: newValue
  }, { merge: true }).then(function() {
    console.log(`Variable ${varName} successfully updated to: ${newValue}`);
  }).catch(function(error) {
    console.error(`Error writing to document for ${varName}`, error);
  });
}

function initLastSlideVisited(user, userDoc, interface, capModule) {
  userDoc.get().then(doc => {
    const lastSlideForModule = activeModule(capModule);
    const lastSlideFSVarValue = doc.data()[lastSlideForModule]

    if (lastSlideFSVarValue === undefined) {
      console.log(`Module first time user detected`)
      // const value = interface.getVariableValue(lastSlideCPVarName)
      // console.log(`CPVal lastSlideVisited ${value}`)
      // Use the above to see what captivate thinks the slide number is
      updateVariable("users", user.uid, lastSlideForModule, 0)
    }
    else {
      console.log(`${lastSlideForModule} (#${lastSlideFSVarValue}) found in FS...returning user to that slide`)
      jumpToSlide(lastSlideFSVarValue)
    }
    lastSlideChangeListener(user, interface, capModule)
  }).catch(function(error) {
    console.log("Failed to initialize last slide visited", error)
  })
}

function activeModule(capModule) {
  switch(capModule) {
    case 'pretest':
      return lastSlideFSVarNamePre;
    case 'posttest':
      return lastSlideFSVarNamePost;
  }
}

function lastSlideChangeListener(user, interface, capModule) {
  const lastSlideForModule = activeModule(capModule);

  cpAPIEventEmitter.addEventListener(
    "CPAPI_VARIABLEVALUECHANGED",
    function() {
      updateVariable(
        "users",
        user.uid,
        lastSlideForModule,
        interface.getVariableValue(lastSlideCPVarName)
      )},
    lastSlideCPVarName
  );
  console.log(`Event listener registered for ${capModule} last slide visited`)
}

function jumpToSlide(slideNum) {
  const getSlides = cp.model.data.project_main.slides.split(",");
  const slideIndex = slideNum - 1

  if (getSlides[slideIndex]) {
    window.cpCmndGotoSlideByUIDAndResume = getSlides[slideIndex].substring(5, getSlides[slideIndex].length);
  }
}

// EXAMPLE: pre-populate users doc with variables
// let userDoc = db.collection('users').doc(user.uid)

// userDoc.get().then(doc => {
//   if (doc.data()) {
//     console.log("Authenticated user already has variables set up in firestore.")
//     return;
//   } else {
//     // this is the user's first login; set up their variables
//     let variablesObj = {}
//     sharedVariables.forEach(name => {
//       variablesObj[name] = 0
//     })
//     userDoc.set(variablesObj)
//     console.log("Successfully set up first-time user's variables")
//   }
// }).catch(function(error) {
//   console.log("Error setting up variables for user", error);
// })
