"use strict";

const SCORM_VERSION = '1.2';
function findScormApi(win, key, maxParents) {
  let nParentsSearched = 0;
  while (!win[key] && win.parent && win.parent !== win && nParentsSearched <= maxParents) {
    nParentsSearched++;
    win = win.parent;
  }
  return win[key] || null;
}
// SCORM 2004 API Discovery Algorithm
// Ref: https://scorm.com/wp-content/assets/old_articles/apifinder/SCORMAPIFinder.htm
function getScorm2004Api() {
  const key = 'API_1484_11';
  const maxParents = 500;
  let API = null;
  if (window.parent && window.parent !== window) {
    API = findScormApi(window.parent, key, maxParents);
  }
  if (!API && window.top.opener) {
    API = findScormApi(window.top.opener, key, maxParents);
  }
  return API;
}
// SCORM 1.2 API Discovery Algorithm
// Ref: https://scorm.com/scorm-explained/technical-scorm/run-time/api-discovery-algorithms/
function getScormApi() {
  const key = 'API';
  const maxParents = 7;
  let API = findScormApi(window, key, maxParents);
  if (!API && window.opener) {
    API = findScormApi(window.opener, key, maxParents);
  }
  return API || null;
}
function getScormApiAdapter() {
  switch (SCORM_VERSION) {
    case '2004v4':
      return getScorm2004Api();
    case '1.2':
      return getScormApi();
    default:
      return null;
  }
}
// Ref: https://scorm.com/scorm-explained/technical-scorm/run-time/run-time-reference/
function getScormWrapper() {
  const STATUS_COMPLETED = 'completed';
  const api = getScormApiAdapter();
  if (!api) {
    return null;
  }
  return {
    init: () => {
      switch (SCORM_VERSION) {
        case '2004v4':
          return api.Initialize('');
        case '1.2':
          return api.LMSInitialize('');
        default:
          return false;
      }
    },
    endSession: () => {
      switch (SCORM_VERSION) {
        case '2004v4':
          return api.Terminate('');
        case '1.2':
          return api.LMSFinish('');
        default:
          return false;
      }
    },
    getLastError: () => {
      switch (SCORM_VERSION) {
        case '2004v4':
          {
            const code = api.GetLastError();
            const message = code ? api.GetErrorString(code) : null;
            return {
              code,
              message
            };
          }
        case '1.2':
          {
            const code = api.LMSGetLastError();
            const message = code ? api.LMSGetErrorString(code) : null;
            return {
              code,
              message
            };
          }
        default:
          return null;
      }
    },
    isCourseCompleted: () => {
      let status = null;
      switch (SCORM_VERSION) {
        case '2004v4':
          status = api.GetValue('cmi.completion_status');
          break;
        case '1.2':
          status = api.LMSGetValue('cmi.core.lesson_status');
          break;
        default:
          break;
      }
      return status === STATUS_COMPLETED;
    },
    setCourseCompleted: () => {
      switch (SCORM_VERSION) {
        case '2004v4':
          api.SetValue('cmi.completion_status', STATUS_COMPLETED);
          return api.Commit('');
        case '1.2':
          api.LMSSetValue('cmi.core.lesson_status', STATUS_COMPLETED);
          return api.LMSCommit('');
        default:
          return false;
      }
    }
  };
}
let scormWrapper = null;
let finished = false;
window.onload = () => {
  const completionCriteria = Number('100');
  console.log('Init:', {
    scormVersion: SCORM_VERSION,
    completionCriteria
  });
  scormWrapper = getScormWrapper();
  if (!scormWrapper) {
    console.error('LMS API is not available.');
    return;
  }
  const initialized = scormWrapper.init();
  if (!initialized) {
    console.error('Failed to initialize communication session with LMS.');
    return;
  }
  let completed = scormWrapper.isCourseCompleted();
  const video = document.getElementById('video-c3ce8aa0-5265-4675-98ca-c53c778a5ed8');
  video.addEventListener('timeupdate', () => {
    if (completed || !scormWrapper) {
      return;
    }
    const minWatchedSec = Math.floor(video.duration * completionCriteria / 100);
    if (video.currentTime >= minWatchedSec) {
      if (scormWrapper.setCourseCompleted()) {
        completed = true;
        console.log('Course completed.', {
          duration: video.duration,
          required: minWatchedSec,
          watched: video.currentTime
        });
      } else {
        const lastError = scormWrapper.getLastError();
        console.error('Failed to set course as completed in LMS.', {
          lastError
        });
      }
    }
  });
};
window.onbeforeunload = () => {
  if (scormWrapper && !finished) {
    finished = scormWrapper.endSession();
  }
};