import { Component, h, Host, Prop, State } from "@stencil/core";
import ZoomImage from '../../../../../assets/Zoom.svg';
import GoogleCalendarImage from '../../../../../assets/Google-Calendar.svg';
import GoogleMeetImage from '../../../../../assets/Google-Meet.svg';
import MicrosoftTeamsImage from '../../../../../assets/Microsoft-Teams.svg';
import OutlookImage from '../../../../../assets/Outlook.svg';
import { getSessionDetails } from "../../util/session";
import { MentornityBridgeApi } from "../../api/mentorinty-bridge-api";
import { mentornityApiEndpoint } from "../../constants/env";
import { createMentornityApiInstance } from "src/modules/mentornity-js-client";
import { Config } from "src/modules/mentornity-js-client/models";
import { SozlukApi } from "@dvn/sozluk/api";
import { sozlukEntries } from "../sozluk-entries";
import { mentornityIntegrationSettingsWrapperI18nDefault, MentornityIntegrationSettingsWrapperI18nKey } from "./i18n";
import { injectNotifier } from "@dvn/alaca/global/notifier";
const updateQueryStringParameter = (uri, key, value) => {
  const re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i');
  const separator = uri.indexOf('?') !== -1 ? '&' : '?';
  if (uri.match(re)) {
    return uri.replace(re, '$1' + key + '=' + value + '$2');
  }
  else {
    return uri + separator + key + '=' + value;
  }
};
const platformConncetionToggle = (mentornityApi, userId, conncetType, disconncetType, isAuthenticated, notifier, strings) => {
  if (isAuthenticated) {
    mentornityApi.removeOAuth(userId, disconncetType)
      .then(() => {
      // display message
      notifier.congratulate(strings.disconnectedSuccessfully);
      // then refresh the page after 1s
      setTimeout(() => {
        window.location.reload();
      }, 1000);
    }, error => console.log(error));
  }
  else {
    mentornityApi.getPlatformOAuthURL(conncetType)
      .then((response) => {
      // redirect user to the authorization page within the same tab
      // the 'state' parameter we send here will be returned to the OAuth2Callback
      // component and that component will handle the account connection
      const url = updateQueryStringParameter(response[conncetType], 'state', location.host);
      window.open(url, '_self');
    }, error => console.log(error));
  }
};
export class MentornityIntegrationSettingsWrapper {
  constructor() {
    this.viewConfig = () => {
      const { userId, isGoogleAuthenticated, isZoomAuthenticated, isMicrosoftAuthenticated, isMicrosoftBusinessAuthenticated } = this.contextParams;
      const { strings, notifier } = this;
      return [
        {
          title: strings.googleAndCalendar,
          description: strings.googleDescription,
          images: [GoogleCalendarImage, GoogleMeetImage],
          onClick: () => platformConncetionToggle(this.mentornityApi, userId, 'googleAuthUrl', 'google', isGoogleAuthenticated, notifier, strings),
          isConnected: isGoogleAuthenticated
        },
        {
          title: strings.zoom,
          description: strings.zoomDescription,
          images: [ZoomImage],
          onClick: () => platformConncetionToggle(this.mentornityApi, userId, 'zoomAuthUrl', 'zoom', isZoomAuthenticated, notifier, strings),
          isConnected: isZoomAuthenticated
        },
        {
          title: strings.outlookCalendar,
          description: strings.outlookDescription,
          images: [OutlookImage],
          onClick: () => platformConncetionToggle(this.mentornityApi, userId, 'microsoftAuthUrl', 'microsoft', isMicrosoftAuthenticated, notifier, strings),
          isConnected: isMicrosoftAuthenticated
        },
        {
          title: strings.microsoftTeams,
          description: strings.microsoftTeamsDescription,
          images: [MicrosoftTeamsImage],
          onClick: () => platformConncetionToggle(this.mentornityApi, userId, 'microsoftBusinessAuthUrl', 'microsoftbusiness', isMicrosoftBusinessAuthenticated, notifier, strings),
          isConnected: isMicrosoftBusinessAuthenticated
        }
      ];
    };
  }
  async componentWillLoad() {
    const { context, headers } = getSessionDetails();
    const { organisationId } = context;
    const { language } = this.contextParams;
    // Setup configuration
    const apiSozluk = new SozlukApi().setLanguage(language).setContents(sozlukEntries);
    this.strings = await apiSozluk.getContent(MentornityIntegrationSettingsWrapperI18nKey, mentornityIntegrationSettingsWrapperI18nDefault);
    const mentornityBridgeApi = new MentornityBridgeApi(mentornityApiEndpoint, context, headers);
    const mentornityApi = createMentornityApiInstance(mentornityApiEndpoint, headers);
    mentornityApi.getOrganisationConfig(organisationId)
      .then((response) => {
      mentornityBridgeApi.organisationConfig = Config.decode(response);
    });
    this.mentornityApi = mentornityApi;
  }
  render() {
    const view = this.viewConfig();
    return (h(Host, null,
      h("mentornity-root-wrapper", { class: "d-block pt-4", theme: { cornerRadius: '15px' } },
        h("div", { class: "row" },
          h("div", { class: "col-12" },
            h("h3", null, this.strings.integration)),
          view.map((platform, i) => (h("div", { class: "col-md-6", key: i },
            h("mentornity-platform-integration-widget", { images: platform.images, title: platform.title, description: platform.description, onConncet: platform.onClick, isConnected: platform.isConnected, strings: this.strings }))))))));
  }
  static get is() { return "mentornity-integration-settings-wrapper"; }
  static get properties() { return {
    "notifier": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Notifier",
        "resolved": "Notifier",
        "references": {
          "Notifier": {
            "location": "import",
            "path": "@dvn/alaca/global/notifier/models"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "contextParams": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "MentornityContextParams",
        "resolved": "MentornityContextParams",
        "references": {
          "MentornityContextParams": {
            "location": "import",
            "path": "../../util/session"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    }
  }; }
  static get states() { return {
    "mentornityApi": {},
    "strings": {}
  }; }
}
injectNotifier(MentornityIntegrationSettingsWrapper);
