export const utopiaUrn = 'dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6cGtxYjhrbHBnZWtsZ2tlbHBzanBoYzljMm5neXhtbjY0cXZocHNhcXVodjQ2emVuLWJhc2ljLWFwcC8yNi4wMS4xNiUyMC0lMjBFeHBvcnQlMjBUTUIlMjAtJTIwUGhhbiUyMG1lbS5kd2c';
export const blankUrn = 'dXJuOmFkc2sub2JqZWN0czpvcy5vYmplY3Q6cGtxYjhrbHBnZWtsZ2tlbHBzanBoYzljMm5neXhtbjY0cXZocHNhcXVodjQ2emVuLWJhc2ljLWFwcC9ibGFuay5kd2c';

export async function getAccessToken(callback) {
  try {
    const { access_token, expires_in } = await $fetch('/api/apsAuthToken');
    callback(access_token, expires_in);
  } catch (err) {
    console.error('Could not obtain access token. Error:', err);
  }
}

export function loadModel(viewer, urn, xform) {
  return new Promise((resolve, reject) => {
    function onDocumentLoadSuccess(doc) {
      const viewable = doc.getRoot().getDefaultGeometry();
      const options = {
        keepCurrentModels: true,
      };
      if (xform) {
        options.placementTransform = xform;
      }
      viewer.loadDocumentNode(doc, viewable, options).then(resolve).catch(reject);
    }
    function onDocumentLoadFailure(code, message, errors) {
      reject({ code, message, errors });
    }
    viewer.setLightPreset(0);
    Autodesk.Viewing.Document.load(`urn:${urn}`, onDocumentLoadSuccess, onDocumentLoadFailure);
  });
}

function showNotification(message) {
  const overlay = document.getElementById('overlay');
  overlay.innerHTML = `<div class="notification">${message}</div>`;
  overlay.style.display = 'flex';
}

function clearNotification() {
  const overlay = document.getElementById('overlay');
  overlay.innerHTML = '';
  overlay.style.display = 'none';
}

export async function setupModelSelection(viewer) {
  if (window.onModelSelectedTimeout) {
    clearTimeout(window.onModelSelectedTimeout);
    delete window.onModelSelectedTimeout;
  }

  try {
    const res = await $fetch(`/api/models/${utopiaUrn}/status`);
    const { status } = res;
    switch (status.status) {
      case 'n/a':
        showNotification(`Model has not been translated.`);
        break;
      case 'inprogress':
        showNotification(`Model is being translated (${status.progress})...`);
        window.onModelSelectedTimeout = setTimeout(onModelSelected, 5000, viewer, utopiaUrn);
        break;
      case 'failed':
        showNotification(
          `Translation failed. <ul>${status.messages.map((msg) => `<li>${JSON.stringify(msg)}</li>`).join('')}</ul>`,
        );
        break;
      default:
        clearNotification();
        loadModel(viewer, utopiaUrn);
        break;
    }
  } catch (err) {
    console.error('Could not load model. Error:', err);
  }
}
