import { h } from '@stencil/core';
import { delay, ServiceBusAdministrationClient, ServiceBusClient } from "@azure/service-bus";
export class SwSselistner {
  constructor() {
    this.baseUrl = '';
    this.baseUrlInteral = 'app.dev.synbee';
    this.pathInternal = [`services/eolo-api-gateway/external-api-sse/`];
    this.deleteMod = false;
    this.pluginActions = [];
    this.pluginActionsState = [];
    this.baseUrlState = undefined;
    this.connectionStringInput = "Endpoint=sb://project-eolo.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=X1zn/rH55oTPiRK3tnaAG+EQHWClSFm00A8LSQSXv2s=";
    this.connectionString = "Endpoint=sb://project-eolo.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=X1zn/rH55oTPiRK3tnaAG+EQHWClSFm00A8LSQSXv2s=";
    this.topicNameInput = "dev-webcomponent";
    this.topicName = "dev-webcomponent";
  }
  changeDeleteMod(newValue) {
    console.log('The new value of activated is: ', newValue);
    const deleteModCopy = newValue;
    this.deleteMod = deleteModCopy;
    console.log('new value from watch: ' + deleteModCopy);
  }
  async getSBus(data, subsciptionName) {
    console.log(subsciptionName);
    try {
      // await this.sender.sendMessages({body:data, subject:`notifications-${subsciptionName}`, correlationId: "important" });
      await this.sender.sendMessages({ body: data });
      // await this.sender.close();
    }
    finally {
      // await this.sbClient.close();
    }
  }
  async deleteSubscriptions(name) {
    this.sbAdministrationClient = new ServiceBusAdministrationClient(this.connectionString);
    this.sbAdministrationClient.deleteSubscription(`${this.topicName}`, `notifications-${name}`, { requestOptions: { allowInsecureConnection: true } }).then(() => console.log(`notifications-${name} sub deleted`));
  }
  async createSubscriptions(name) {
    const nameRegex = name.includes(' ') ? name.replace(' ', '_') : name;
    const subs = await this.sbAdministrationClient.subscriptionExists(`${this.topicName}`, `notifications-${nameRegex}`);
    if (!subs) {
      this.sbAdministrationClient.createSubscription(`${this.topicName}`, `notifications-${nameRegex}`, {
        defaultRuleOptions: {
          name: "ImportantCorrelationRule",
          filter: { subject: `notifications-${nameRegex}`, correlationId: "important" },
        },
      });
    }
  }
  async checkOrCreateTopic() {
    if (await this.sbAdministrationClient.topicExists(`${this.topicName}`)) {
      await this.sbAdministrationClient.createTopic(`${this.topicName}`);
    }
  }
  componentWillRender() {
    this.connectionString = this.connectionStringInput;
    this.topicName = this.topicNameInput;
    if (this.deleteMod) {
      this.pluginActions.forEach((pluginAction) => {
        if (this.checkForSse(this.baseUrl, pluginAction.id)) {
          this.deleteSubscriptions(pluginAction.name);
        }
      });
    }
    else {
      // connection string to your Service Bus namespace
      // create a Service Bus client using the connection string to the Service Bus namespace
      this.sbClient = new ServiceBusClient(this.connectionString);
      this.sbAdministrationClient = new ServiceBusAdministrationClient(this.connectionString);
      // this.checkOrCreateTopic();
      this.sender = this.sbClient.createSender(this.topicName);
      this.baseUrlState = this.baseUrl;
      this.pluginActionsState = [...this.pluginActions];
      this.pluginActionsState.forEach((pluginAction, index) => {
        if (this.checkForSse(this.baseUrlState, pluginAction.id)) {
          // this.createSubscriptions(pluginAction.name)
          setTimeout(() => this.connectToSse(this.baseUrlState, pluginAction), index * 2000);
        }
      });
    }
  }
  checkForSse(baseUrl, path) {
    let check = false;
    if (baseUrl && path && baseUrl !== '' && path !== '') {
      check = true;
    }
    return check;
  }
  filterPostChain(data) {
    return data.type;
  }
  connectToSse(baseUrl, path) {
    delay(2000);
    setTimeout(() => {
      const eventSource = new EventSource(`https://${baseUrl}/${path.id}`);
      if (eventSource) {
        eventSource.addEventListener("message", async (e) => {
          const messageData = JSON.parse(e.data);
          // if(messageData?.eventType !== 'OK' && messageData?.eventType !== 'ONLINE'){
          this.getSBus(messageData, path.name);
          // }
        });
      }
    }, 2000);
  }
  render() {
    return (h("div", null));
  }
  static get is() { return "sw-sselistner"; }
  static get encapsulation() { return "shadow"; }
  static get originalStyleUrls() {
    return {
      "$": ["sw-sselistner.css"]
    };
  }
  static get styleUrls() {
    return {
      "$": ["sw-sselistner.css"]
    };
  }
  static get properties() {
    return {
      "baseUrl": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "base-url",
        "reflect": false,
        "defaultValue": "''"
      },
      "baseUrlInteral": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "base-url-interal",
        "reflect": false,
        "defaultValue": "'app.dev.synbee'"
      },
      "pathInternal": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "string[]",
          "resolved": "string[]",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "defaultValue": "[`services/eolo-api-gateway/external-api-sse/`]"
      },
      "deleteMod": {
        "type": "boolean",
        "mutable": true,
        "complexType": {
          "original": "boolean",
          "resolved": "boolean",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "delete-mod",
        "reflect": false,
        "defaultValue": "false"
      },
      "pluginActions": {
        "type": "unknown",
        "mutable": true,
        "complexType": {
          "original": "{id:string, info:string, name:string}[]",
          "resolved": "{ id: string; info: string; name: string; }[]",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "defaultValue": "[]"
      },
      "connectionStringInput": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "connection-string-input",
        "reflect": false,
        "defaultValue": "\"Endpoint=sb://project-eolo.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=X1zn/rH55oTPiRK3tnaAG+EQHWClSFm00A8LSQSXv2s=\""
      },
      "topicNameInput": {
        "type": "string",
        "mutable": true,
        "complexType": {
          "original": "string",
          "resolved": "string",
          "references": {}
        },
        "required": false,
        "optional": false,
        "docs": {
          "tags": [],
          "text": ""
        },
        "attribute": "topic-name-input",
        "reflect": false,
        "defaultValue": "\"dev-webcomponent\""
      }
    };
  }
  static get states() {
    return {
      "pluginActionsState": {},
      "baseUrlState": {},
      "connectionString": {},
      "topicName": {}
    };
  }
  static get watchers() {
    return [{
        "propName": "deleteMod",
        "methodName": "changeDeleteMod"
      }];
  }
}
