import { globalEventName, GLOBALEVENTS } from "../../../configuration/constants";
import updateComponentAttr from './scriptEvents/updateComponentAttr';
import evalScripts from './scriptEvents/eval';
import showComponent from './scriptEvents/showComponent';
import hideComponent from './scriptEvents/hideComponent';
import loadComponent from './scriptEvents/loadComponent';

const EventManager = (editor, opts = {}) => {
  if (!editor.EventManager) {
    editor.EventManager = { events: [] }
  }
};

export const componentEventHandler = {
  getJs: function () {
    return `
      let events = this.getAttribute('data-events');

      if (events) {
        events = JSON.parse(events);

        events.forEach && events.forEach(function (event) {
          PubSub.unsubscribe(event.target);
          const $source = $('#' + event.source);

          $source.on(event.action, () => {
            PubSub.publish(event.target + '.' + event.result);
          })
        });
      }
    `
  }
}

export const handleGlobalEvents = () => `
  if (window.spSocket) {
    function nav(url, isNewWindow) {
      if (isNewWindow) {
        window.open(url, '_blank');
      } else {
        window.location.href = url;
      }
    }

    window.spSocket.subscribe({ eventName: '${globalEventName}', callback: function(data) {
      if (!data) return;

      switch(data.type) {
        ${updateComponentAttr.getJs()};
        ${evalScripts.getJs()};
        ${showComponent.getJs()};
        ${hideComponent.getJs()};
        ${loadComponent.getJs()};
      }
    }});

    window.addEventListener('load', function() {
      if (window.ee) {
        window.ee.emit('resize-onload');
      }
    });
  }
`

export const globalEventHandler = {
  getJs: function () {
    return `
      ${handleGlobalEvents()}
    `;
  }
}

export default EventManager;
