import 'whatwg-fetch';
import React from 'react';
import { render } from 'react-dom';
import CorePlugin, { utils } from '@annotation-studio/plugin-core';
import ViewerPlugin from '@annotation-studio/plugin-viewer';
import ResourceEditorPlugin from '@annotation-studio/plugin-resource-editor';
import { TaggingAnnotationsPlugin, TaggingPlugin } from '@annotation-studio/plugin-tagging';
import TranscriberPlugin from '@annotation-studio/plugin-transcriber';
import DraftsPlugin from '@annotation-studio/plugin-drafts';
import JsonPreviewPlugin from '@annotation-studio/plugin-json-preview';

var behaviours = function behaviours(resolveSharedStore) {
  return {
    'annotation-studio-core': function annotationStudioCore(image, attributes) {
      return CorePlugin(image, attributes).then(function (store) {
        return resolveSharedStore(store);
      });
    },
    'annotation-studio-viewer': ViewerPlugin,
    'annotation-studio-resource-editor': ResourceEditorPlugin,
    'annotation-studio-tagging-annotations': TaggingAnnotationsPlugin,
    'annotation-studio-tagging': TaggingPlugin,
    'annotation-studio-drafts': DraftsPlugin,
    'annotation-studio-transcriber': TranscriberPlugin,
    'annotation-studio-json-preview': JsonPreviewPlugin
  };
};

var _utils$deferred = utils.deferred(),
    resolve = _utils$deferred.resolve,
    whenToRender = _utils$deferred.promise;

function loadPlugin($el, name, config) {
  try {
    var register = behaviours(resolve);
    var behaviour = register[name];
    if (behaviour.length === 3) {
      whenToRender.then(function (store) {
        return behaviour($el, config, store);
      });
    } else {
      behaviour($el, config);
    }
  } catch (e) {
    console.error('Behaviour does not exist: ' + name, e);
  }
}

document.addEventListener('DOMContentLoaded', function () {
  // Small error-prone example of data behaviour factory.
  for (var _iterator = document.querySelectorAll('[data-behaviour]'), _isArray = Array.isArray(_iterator), _i = 0, _iterator = _isArray ? _iterator : _iterator[Symbol.iterator]();;) {
    var _ref;

    if (_isArray) {
      if (_i >= _iterator.length) break;
      _ref = _iterator[_i++];
    } else {
      _i = _iterator.next();
      if (_i.done) break;
      _ref = _i.value;
    }

    var $el = _ref;

    loadPlugin($el, $el.getAttribute('data-behaviour'), utils.getAttributes($el));
  }
});

// Set up a global.
(function (g) {
  g.loadAnnotationStudioPlugin = g.loadAnnotationStudioPlugin ? g.loadAnnotationStudioPlugin : loadPlugin;
})(window || global);