ModelViewer = ModelViewer.default;

const common = ModelViewer.common;
const math = common.math;
const glMatrix = common.glMatrix;
const vec3 = glMatrix.vec3;
const quat = glMatrix.quat;

function wc3PathSolver(src) {
  src = localOrHive(src.toLowerCase().replace(/\\/g, '/'));

  return [src, src.substr(src.lastIndexOf('.')), true];
}

let statusElement = document.getElementById('status');
statusElement.textContent = 'Initializing the viewer';

let canvas = document.getElementById('canvas');
let viewer = new ModelViewer.viewer.ModelViewer(canvas);

viewer.addHandler(ModelViewer.viewer.handlers.mdx);

let scene = viewer.addScene();

let thingsLoading = [];

function updateStatus() {
  if (thingsLoading.length) {
    statusElement.textContent = `Loading ${thingsLoading.join(', ')}`;
  } else {
    statusElement.textContent = '';
  }
}

for (let resource of viewer.resourcesLoading) {
  let path = resource.fetchUrl;
  let file = path.slice(path.lastIndexOf('/') + 1);

  if (file !== '') {
    thingsLoading.push(file);
  }
}

updateStatus();

viewer.on('error', (target, error, reason) => {
  console.log('ERROR', error, reason, target);
});

viewer.on('loadstart', (target) => {
  let path = target.fetchUrl;

  // PromiseResource has no path, nor does it need to be tracked.
  if (path) {
    let file = path.slice(path.lastIndexOf('/') + 1);

    if (file !== '') {
      thingsLoading.push(file);
      updateStatus();
    }
  }
});

viewer.on('loadend', (target) => {
  let path = target.fetchUrl;

  // PromiseResource has no path, nor does it need to be tracked.
  if (path) {
    let file = path.slice(path.lastIndexOf('/') + 1);

    if (file !== '') {
      let index = thingsLoading.indexOf(file);

      if (index !== -1) {
        thingsLoading.splice(index, 1);
        updateStatus();
      }
    }
  }
});

setupCamera(scene, 500);

(function step() {
  requestAnimationFrame(step);

  viewer.updateAndRender();
}());

// const model = viewer.load('Units/Naga/NagaSiren/NagaSiren.mdx', wc3PathSolver);
// const instance = model.addInstance();

// instance.setScene(scene);

// instance.setSequence(4);
// instance.setSequenceLoopMode(2);
// viewer.frameTime = 5;


const model = viewer.load('TohsakaRin.mdx', (src) => {
  return [`../../../resources/TohsakaRin/${src}`, src.substr(src.lastIndexOf('.')), true]
});

const instance = model.addInstance();

instance.setScene(scene);
instance.setSequence(1);
instance.setSequenceLoopMode(2);
//viewer.frameTime = 5;
