'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

const index = require('./index-1141a245.js');
const index$2 = require('./index-9fd84b93.js');
const index$1 = require('./index-61f9621a.js');
const dataTransferField = require('./data-transfer-field-e8417d5f.js');
require('./index-2eea69a0.js');
const listFetchState = require('./list-fetch-state-a9e880b1.js');
const date = require('./date-a24d7714.js');
const index$3 = require('./index-9d3d3d15.js');
const Equal = require('./Equal-e7239026.js');
const rawData = require('./raw-data-34f1739c.js');
require('./FieldGenerator-279a646b.js');
require('./BaseField-381327a9.js');
require('./data-model-9afb7f54.js');
require('./InterceptorHandler-09a1e84b.js');

function generateBase64ForAPIKey(createAPIKeyResponse) {
  return btoa(`${createAPIKeyResponse.keyId}:${createAPIKeyResponse.key}`);
}
const KimlikApiKeyForm = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.onSubmitForm = (event) => {
      const { values } = event.detail;
      const { name, scopes } = values;
      const body = {
        name,
        scopes: (scopes || []).map(scope => scope.value),
      };
      const promise = values._id
        ? this.apiKimlik.updateApiKey(values._id, body)
        : this.apiKimlik.createApiKey(body);
      this.isPending = true;
      promise.then((response) => {
        if (response.key) {
          // a new key created. show the key value
          this.createAPIKeyResponse = response;
        }
        else {
          // an existing key is updated
          this.onChange();
        }
      })
        .finally(() => this.isPending = false);
    };
  }
  render() {
    var _a;
    const { isPending, item, createAPIKeyResponse } = this;
    return (index.h(index.Host, null, createAPIKeyResponse
      ? index.h("div", null, index.h("p", null, "The credentials of your new API Key are"), index.h("table", null, index.h("tr", null, index.h("td", null, "Key ID"), index.h("td", null, index.h("dvn-highlighted-code", { textToCopy: createAPIKeyResponse.keyId, condensed: true, leaned: true }, index.h("span", null, createAPIKeyResponse.keyId)))), index.h("tr", null, index.h("td", null, "Key"), index.h("td", null, index.h("dvn-highlighted-code", { textToCopy: createAPIKeyResponse.key, condensed: true, leaned: true }, index.h("span", null, createAPIKeyResponse.key))))), index.h("dvn-alert", { tint: "warning", message: "This is the only time you can view the Key value. Please save it in a secure place." }), index.h("br", null), index.h("p", null, "If you're going to use this API Key with Kimlik, then you should", index.h("ul", null, index.h("li", null, "concatenate the key ID and the key with a colon"), index.h("li", null, "encode it with base 64"), index.h("li", null, "put it in the request header with ", index.h("code", null, "api-key"), " name"))), index.h("br", null), index.h("p", null, "Base 64 encoded value of your key id and key is"), index.h("dvn-highlighted-code", { textToCopy: generateBase64ForAPIKey(createAPIKeyResponse), condensed: true, leaned: true }, index.h("span", null, generateBase64ForAPIKey(createAPIKeyResponse))), index.h("div", { class: "d-flex justify-content-end mt-3" }, index.h("dvn-button", { leaned: true, onClick: this.onChange }, "OK")))
      : index.h("doldurma-form", { fields: [
          new dataTransferField.DataTransferField('_id')
            .setValue(item === null || item === void 0 ? void 0 : item._id),
          new index$1.TextField('name', 'Name')
            .setValue(item === null || item === void 0 ? void 0 : item.name)
            .require(),
          new index$2.SubFormField('scopes', 'Scopes', [
            new index$1.TextField('value', '', 'Scope name or URI')
              .require(),
          ]).setMaxCount(10)
            .setValue((_a = item === null || item === void 0 ? void 0 : item.scopes) === null || _a === void 0 ? void 0 : _a.map(scope => ({ value: scope }))),
        ], onSubmit: this.onSubmitForm, submitButtonLabel: item ? 'Update' : 'Create', progressing: isPending })));
  }
};

const KimlikApiKeyList = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.list = listFetchState.ListFetchState.init();
  }
  componentWillLoad() {
    this.fetchList();
  }
  async fetchList() {
    const { list } = this;
    this.list = this.list.beforeFetch();
    const response = await this.apiKimlik.getApiKeys().catch(error => {
      this.list = list.afterFetchError(error);
    });
    if (!response)
      return;
    this.list = list.afterFetch(response, false);
  }
  render() {
    const { list } = this;
    return (index.h(index.Host, { class: "container d-flex flex-grow-1 flex-column" }, index.h("dvn-list-view-table", { config: {
        actions: [
          {
            ui: {
              name: 'edit',
              buttonType: 'icon-button',
              iconName: 'uil uil-pen',
              view: 'flat',
            },
          },
          {
            ui: {
              name: 'delete',
              buttonType: 'icon-button',
              iconName: 'uil uil-trash',
              view: 'flat',
              tint: 'danger',
            },
          },
        ],
        fields: [
          { fieldId: 'name' },
          { fieldId: 'keyId' },
          { fieldId: '_created' },
        ]
      }, fields: [
        new index$1.TextField('name', 'Name'),
        new index$1.TextField('keyId', 'Key ID'),
        new date.DateField('_created', 'Creation Date'),
      ], items: (list.data || []).sort((a, b) => a.name.localeCompare(b.name)), isEndReached: list.isEndReached(), isProgressing: list.isPending, error: list.error ? 'Fetching list failed' : undefined, onRetry: () => this.fetchList(), scrollToFit: true })));
  }
};

const KimlikSAMLConfigForm = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.onSubmitForm = (event) => {
      const { values } = event.detail;
      console.log(values);
      const { name, metadataURL, metadataContent, assertionConsumerServiceURL, audienceURI, serviceProviderIssuer, attributeKeyMappingTemplate, metaAttributeKeyMapping: metaAttributeKeyMappingArray = [] } = values;
      const metaAttributeKeyMapping = {};
      metaAttributeKeyMappingArray.forEach(keyValuePair => {
        if (keyValuePair.key && keyValuePair.value) {
          metaAttributeKeyMapping[keyValuePair.key] = keyValuePair.value;
        }
      });
      const body = {
        name,
        metadataURL: metadataContent ? undefined : metadataURL,
        metadataContent: metadataURL ? undefined : metadataContent,
        assertionConsumerServiceURL,
        audienceURI,
        serviceProviderIssuer,
        attributeKeyMappingTemplate,
        metaAttributeKeyMapping
      };
      const promise = values._id
        ? this.apiKimlik.updateSAMLConfig(values._id, body)
        : this.apiKimlik.createSAMLConfig(body);
      this.isPending = true;
      promise.then(this.onChange)
        .finally(() => this.isPending = false);
    };
  }
  render() {
    const { isPending, item } = this;
    return (index.h(index.Host, null, index.h("doldurma-form", { fields: [
        new dataTransferField.DataTransferField('_id')
          .setValue(item === null || item === void 0 ? void 0 : item._id),
        new index$1.TextField('name', 'Name')
          .setValue(item === null || item === void 0 ? void 0 : item.name)
          .require(),
        new index$3.SingleChoiceField('metadataSource', 'Metadata source', [
          { label: 'URL', value: 'url' },
          { label: 'XML File Content', value: 'raw' },
        ], '', 'select', 'Metadata Source')
          .setValue((item === null || item === void 0 ? void 0 : item.metadataContent) ? 'raw' : 'url')
          .require(),
        new index$1.TextField('metadataURL', 'Metadata URL')
          .setInputType('url')
          .setValue(item === null || item === void 0 ? void 0 : item.metadataURL)
          .addInterceptor('onFormChange', new Equal.ConcealerConditional(new Equal.Equal('metadataSource', 'url')))
          .require(),
        new index$1.TextField('metadataContent', 'Metadata File Content (XML)')
          .setLinesMax(10)
          .setLines(10)
          .setValue(item === null || item === void 0 ? void 0 : item.metadataContent)
          .addInterceptor('onFormChange', new Equal.ConcealerConditional(new Equal.Equal('metadataSource', 'raw')))
          .require(),
        new index$1.TextField('assertionConsumerServiceURL', 'Assertion Consumer Service URL')
          .setInputType('url')
          .setValue(item === null || item === void 0 ? void 0 : item.assertionConsumerServiceURL)
          .require(),
        new index$1.TextField('audienceURI', 'Audience URI')
          .setInputType('url')
          .setValue(item === null || item === void 0 ? void 0 : item.audienceURI)
          .require(),
        new index$1.TextField('serviceProviderIssuer', 'Service Provider Issuer')
          .setInputType('url')
          .setValue(item === null || item === void 0 ? void 0 : item.serviceProviderIssuer)
          .require(),
        new index$3.SingleChoiceField('attributeKeyMappingTemplate', 'Attribute mapping template', [
          { label: 'Azure AD', value: 'azure-ad' },
        ], 'By default the user details are expected to be found as Email, FirstName and LastName in the SAML response. You may choose predefined SAML token claims for well known SAML providers.', 'select', 'None')
          .setValue(item === null || item === void 0 ? void 0 : item.attributeKeyMappingTemplate),
        new index$2.SubFormField('metaAttributeKeyMapping', 'Meta attribute key mapping', [
          new index$1.TextField('key', '', 'Key appears in user.meta').require(),
          new index$1.TextField('value', '', 'Key appears in SAML response').require(),
        ], 'User data sent to the consumer API only contains email, firstName and lastName. You can get extra token values sent by SAML provider and receive them in user.meta object by defining the user.meta field keys and their corresponding SAML token claims.', 'horizontal').setMaxCount(10)
          .setValue(Object.entries((item === null || item === void 0 ? void 0 : item.metaAttributeKeyMapping) || {}).map(([key, value]) => ({ key, value }))),
      ], onSubmit: this.onSubmitForm, submitButtonLabel: item ? 'Update' : 'Create', progressing: isPending })));
  }
};

const KimlikSAMLConfigList = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.list = listFetchState.ListFetchState.init();
  }
  componentWillLoad() {
    this.fetchList();
  }
  async fetchList() {
    const { list } = this;
    this.list = this.list.beforeFetch();
    const response = await this.apiKimlik.getSAMLConfigs().catch(error => {
      this.list = list.afterFetchError(error);
    });
    if (!response)
      return;
    this.list = list.afterFetch(response, false);
  }
  render() {
    const { list } = this;
    return (index.h(index.Host, { class: "container d-flex flex-grow-1 flex-column" }, index.h("dvn-list-view-table", { config: {
        actions: [
          {
            ui: {
              name: 'edit',
              buttonType: 'icon-button',
              iconName: 'uil uil-pen',
              view: 'flat',
            },
          },
          {
            ui: {
              name: 'delete',
              buttonType: 'icon-button',
              iconName: 'uil uil-trash',
              view: 'flat',
              tint: 'danger',
            },
          },
        ],
        fields: [
          { fieldId: 'name' },
          { fieldId: '_created' },
          { fieldId: '_id' },
        ]
      }, fields: [
        new index$1.TextField('name', 'Name'),
        new date.DateField('_created', 'Creation Date'),
        new rawData.RawDataField('_id', 'ID'),
      ], items: (list.data || []).sort((a, b) => { var _a; return (_a = a.name) === null || _a === void 0 ? void 0 : _a.localeCompare(b.name); }), isEndReached: list.isEndReached(), isProgressing: list.isPending, error: list.error ? 'Fetching list failed' : undefined, onRetry: () => this.fetchList(), scrollToFit: true })));
  }
};

const KimlikUserList = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.list = listFetchState.ListFetchState.init();
  }
  componentWillLoad() {
    this.fetchList();
  }
  async fetchList() {
    const { list } = this;
    this.list = this.list.beforeFetch();
    const response = await this.apiKimlik.getUsers().catch(error => {
      this.list = list.afterFetchError(error);
    });
    if (!response)
      return;
    this.list = list.afterFetch(response, false);
  }
  render() {
    const { list } = this;
    return (index.h(index.Host, { class: "container d-flex flex-grow-1 flex-column" }, index.h("dvn-list-view-table", { config: {
        actions: [
        // {
        //   ui: {
        //     name: 'edit',
        //     buttonType: 'icon-button',
        //     iconName: 'uil uil-pen',
        //     view: 'flat',
        //   },
        // },
        // {
        //   ui: {
        //     name: 'delete',
        //     buttonType: 'icon-button',
        //     iconName: 'uil uil-trash',
        //     view: 'flat',
        //     tint: 'danger',
        //   },
        // },
        ],
        fields: [
          { fieldId: 'email' },
          { fieldId: 'firstName' },
          { fieldId: 'lastName' },
          { fieldId: '_created' },
        ]
      }, fields: [
        new index$1.TextField('firstName', 'First name'),
        new index$1.TextField('lastName', 'Last name'),
        new index$1.TextField('email', 'Last name').setInputType('email'),
        new date.DateField('_created', 'Creation Date'),
      ], items: (list.data || []).sort((a, b) => a.firstName.localeCompare(b.firstName)), isEndReached: list.isEndReached(), isProgressing: list.isPending, error: list.error ? 'Fetching list failed' : undefined, onRetry: () => this.fetchList(), scrollToFit: true })));
  }
};

exports.kimlik_api_key_form = KimlikApiKeyForm;
exports.kimlik_api_key_list = KimlikApiKeyList;
exports.kimlik_saml_config_form = KimlikSAMLConfigForm;
exports.kimlik_saml_config_list = KimlikSAMLConfigList;
exports.kimlik_user_list = KimlikUserList;
