import Vue from 'vue';

const VueSSE = {
  install(Vue, options) {
    const sse = new EventSource('http://localhost:8990/ees');

    Vue.prototype.$sse = {
      addListener(event, callback) {
        sse.addEventListener(event, (e) => {
          callback(JSON.parse(e.data));
        });
      },
      removeListener(event, callback) {
        sse.removeEventListener(event, callback);
      }
    };

    Vue.mixin({
      created() {
        if (this.$options.sse) {
          this.$options.sse.forEach((eventHandler) => {
            this.$sse.addListener(eventHandler.event, eventHandler.callback);
          });
        }
      },
      beforeDestroy() {
        if (this.$options.sse) {
          this.$options.sse.forEach((eventHandler) => {
            this.$sse.removeListener(eventHandler.event, eventHandler.callback);
          });
        }
      }
    });
  }
};

export default VueSSE;
