var Elm = require('../elm/Main.elm');
var css = require('../css/style.scss');

var helpers = {

  toArray: function (data) {
    return [].slice.call(data);
  },

  buildSelector: function buildSelector(element) {
    var selector      = '';
    var parentElement = element.parentElement;
    var classList     = helpers.toArray(element.classList);

    if (parentElement) {
      selector += buildSelector(parentElement) + ' ';
    }

    selector += element.tagName.toLowerCase();

    if (element.id) {
      selector += '#' + element.id;
    }

    if (classList.length) {
      selector += '.' + classList.join('.');
    }

    return selector;
  },

};

helpers.toArray(
  document.querySelectorAll(
    '[data-module]'
  )
)
.map(function (element) {
  return {
    element: element,
    module: element.dataset.module,
  };
})
.forEach(function (config) {
  if (!(config.module in Elm)) {
    throw new Error(
      '[Elm] Module "%s" bound to "%s" not found in Elm namespace'
      .replace('%s', config.module)
      .replace('%s', helpers.buildSelector(config.element))
    );
  }

  Elm.embed(
    Elm[config.module],
    config.element
  );
});

@@ -80,19 +80,623 @@
 var 
-helpers = %7B
+local = %7B%0A  Main: function (app) %7B%0A    var sse;%0A%0A    console.log('%5BLocal%5D App Main bound');%0A%0A    sse =%0A      helpers.sse('http://localhost:7654/events');%0A%0A    sse.onmessage =%0A      function (event) %7B%0A        var message =%0A          helpers.toJSON(event.data);%0A%0A        console.log('%5BSSE%5D Data received %25o', message);%0A%0A        app.ports.events.send(message.label);%0A%0A        return message;%0A      %7D;%0A  %7D,%0A%7D;%0A%0Avar helpers = %7B%0A%0A  sse: function (endpoint) %7B%0A    return new EventSource(endpoint);%0A  %7D,%0A%0A  toJSON: function (string) %7B%0A    try %7B%0A      return JSON.parse(string);%0A    %7D catch (_) %7B%0A      return %7B%7D;%0A    %7D%0A  %7D,
 %0A%0A  
@@ -1691,16 +1691,26 @@
 ;%0A  %7D%0A%0A 
+ var app =
  Elm.emb
@@ -1759,13 +1759,153 @@
 ment
-%0A  );
+,%0A    %7B events: '' %7D%0A  );%0A%0A  // Once App bound to element, init local js interop%0A  if (local%5Bconfig.module%5D) %7B%0A    local%5Bconfig.module%5D(app);%0A  %7D
 %0A%7D);

Send `EventSource` data to Elm app.