import { Component, Vue } from 'vue-property-decorator';
import { get } from 'lodash';

function parseMessageData(message: MessageEvent<string>) {
  const data = JSON.parse(get(message, 'data', '{}'));
  return data;
}

@Component({})
export default class NotificationsListener extends Vue {

  listener: { (message: MessageEvent<string>): void } | null = null;

  created() {
    this.listener = (message: MessageEvent<string>) => {
      const data = parseMessageData(message);
      return this.handleNotification(data);
    };
    this.$websockets.addListener(this.listener);
  }

  beforeDestroy() {
    if (this.listener) {
      this.$websockets.removeListener(this.listener);
    }
  }

  handleNotification(messageData: any): void {
    console.info(`notification not handled via handleNotification() method in '${this.$options.name}' component!`, messageData);
  }
}