import Websockets, { WebsocketsConfig } from '@services/websockets';
import { PluginFunction, PluginObject, VueConstructor } from 'vue';
import { Vue as _Vue } from 'vue/types/vue';
import { router } from '@/router';
import store from '@/state/store';

interface WebsocketsPlugin<T> extends PluginObject<T> {
  init: (config: WebsocketsConfig) => void;
  install: PluginFunction<T>;
  instance?: {
    websocket: WebSocket | null;
  };
}

interface WebsocketsOptions {
  name: string;
}

const WebsocketsPlugin: WebsocketsPlugin<VueConstructor> = {
  init(config: WebsocketsConfig): void {
    Websockets.create(config);
  },
  install<T extends WebsocketsOptions>(Vue: typeof _Vue, options?: T): void {
    Vue.prototype.$websockets = new Websockets();

    if (options) {
      if (options.name) {
        delete Vue.prototype.$websockets;

        Vue.prototype[options.name] = this.instance;
      }
    }
  },
};

const initWebsockets = setInterval(() => {
  store
    .dispatch('oidcClient/getAccessToken')
    .then((accessToken) => {      
      if (accessToken) {
        WebsocketsPlugin.init({
          router,
          url: `wss://${document.location.host}/service/notifier/gateway/notify/notifier.message.send.push`,
        });
        clearInterval(initWebsockets)
      }
    })
}, 500)

export default WebsocketsPlugin;
