import Vue from "vue";

import { forEachNode } from "./utils";
import Apps from "./apps";

/**
 * Bootstrap Vue.js application at given Element instance.
 *
 * App properties are passed via data attributes, like:
 *
 * <div class="__vue-root" data-message="Hello" data-app="SomeApp"></div>
 *
 * @param {Element} el DOM Element
 */
function renderVueAppElement(el) {
  const attrs = Object.assign({}, el.dataset);

  if (! attrs.app) {
    console.warn(el, 'Cannot bootstrap: missing data-app');
    return;
  }

  const app = Apps[attrs.app];

  if (! app) {
    console.warn(el, `Cannot bootstrap: unknown app ${attrs.app}`);
    return;
  }

  return app(el, attrs);
}


function init(event) {
  // Initialize Vue.js apps.
  forEachNode(document.querySelectorAll('.__js-root'), renderVueAppElement)
}

document.addEventListener('DOMContentLoaded', init);