import { r as registerInstance, h, H as Host } from './index-ecdfb761.js';
import { S as SubFormField } from './index-09efdc01.js';
import { T as TextField } from './index-150b6a59.js';
import { D as DataTransferField } from './data-transfer-field-2f305919.js';
import './index-61dcd269.js';
import { L as ListFetchState } from './list-fetch-state-d8c2f8ef.js';
import { D as DateField } from './date-1bc489bd.js';
import { S as SingleChoiceField } from './index-23baeeef.js';
import { C as ConcealerConditional, E as Equal } from './Equal-8818d86d.js';
import { R as RawDataField } from './raw-data-eb55820e.js';
import './FieldGenerator-3ae403b2.js';
import './BaseField-0b01dc2c.js';
import './data-model-f7ccf826.js';
import './InterceptorHandler-6474bcf4.js';

function generateBase64ForAPIKey(createAPIKeyResponse) {
  return btoa(`${createAPIKeyResponse.keyId}:${createAPIKeyResponse.key}`);
}
const KimlikApiKeyForm = class {
  constructor(hostRef) {
    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 (h(Host, null, createAPIKeyResponse
      ? h("div", null, h("p", null, "The credentials of your new API Key are"), h("table", null, h("tr", null, h("td", null, "Key ID"), h("td", null, h("dvn-highlighted-code", { textToCopy: createAPIKeyResponse.keyId, condensed: true, leaned: true }, h("span", null, createAPIKeyResponse.keyId)))), h("tr", null, h("td", null, "Key"), h("td", null, h("dvn-highlighted-code", { textToCopy: createAPIKeyResponse.key, condensed: true, leaned: true }, h("span", null, createAPIKeyResponse.key))))), h("dvn-alert", { tint: "warning", message: "This is the only time you can view the Key value. Please save it in a secure place." }), h("br", null), h("p", null, "If you're going to use this API Key with Kimlik, then you should", h("ul", null, h("li", null, "concatenate the key ID and the key with a colon"), h("li", null, "encode it with base 64"), h("li", null, "put it in the request header with ", h("code", null, "api-key"), " name"))), h("br", null), h("p", null, "Base 64 encoded value of your key id and key is"), h("dvn-highlighted-code", { textToCopy: generateBase64ForAPIKey(createAPIKeyResponse), condensed: true, leaned: true }, h("span", null, generateBase64ForAPIKey(createAPIKeyResponse))), h("div", { class: "d-flex justify-content-end mt-3" }, h("dvn-button", { leaned: true, onClick: this.onChange }, "OK")))
      : h("doldurma-form", { fields: [
          new DataTransferField('_id')
            .setValue(item === null || item === void 0 ? void 0 : item._id),
          new TextField('name', 'Name')
            .setValue(item === null || item === void 0 ? void 0 : item.name)
            .require(),
          new SubFormField('scopes', 'Scopes', [
            new 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) {
    registerInstance(this, hostRef);
    this.list = 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 (h(Host, { class: "container d-flex flex-grow-1 flex-column" }, 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 TextField('name', 'Name'),
        new TextField('keyId', 'Key ID'),
        new 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) {
    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 (h(Host, null, h("doldurma-form", { fields: [
        new DataTransferField('_id')
          .setValue(item === null || item === void 0 ? void 0 : item._id),
        new TextField('name', 'Name')
          .setValue(item === null || item === void 0 ? void 0 : item.name)
          .require(),
        new 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 TextField('metadataURL', 'Metadata URL')
          .setInputType('url')
          .setValue(item === null || item === void 0 ? void 0 : item.metadataURL)
          .addInterceptor('onFormChange', new ConcealerConditional(new Equal('metadataSource', 'url')))
          .require(),
        new TextField('metadataContent', 'Metadata File Content (XML)')
          .setLinesMax(10)
          .setLines(10)
          .setValue(item === null || item === void 0 ? void 0 : item.metadataContent)
          .addInterceptor('onFormChange', new ConcealerConditional(new Equal('metadataSource', 'raw')))
          .require(),
        new TextField('assertionConsumerServiceURL', 'Assertion Consumer Service URL')
          .setInputType('url')
          .setValue(item === null || item === void 0 ? void 0 : item.assertionConsumerServiceURL)
          .require(),
        new TextField('audienceURI', 'Audience URI')
          .setInputType('url')
          .setValue(item === null || item === void 0 ? void 0 : item.audienceURI)
          .require(),
        new TextField('serviceProviderIssuer', 'Service Provider Issuer')
          .setInputType('url')
          .setValue(item === null || item === void 0 ? void 0 : item.serviceProviderIssuer)
          .require(),
        new 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 SubFormField('metaAttributeKeyMapping', 'Meta attribute key mapping', [
          new TextField('key', '', 'Key appears in user.meta').require(),
          new 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) {
    registerInstance(this, hostRef);
    this.list = 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 (h(Host, { class: "container d-flex flex-grow-1 flex-column" }, 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 TextField('name', 'Name'),
        new DateField('_created', 'Creation Date'),
        new 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) {
    registerInstance(this, hostRef);
    this.list = 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 (h(Host, { class: "container d-flex flex-grow-1 flex-column" }, 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 TextField('firstName', 'First name'),
        new TextField('lastName', 'Last name'),
        new TextField('email', 'Last name').setInputType('email'),
        new 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 })));
  }
};

export { KimlikApiKeyForm as kimlik_api_key_form, KimlikApiKeyList as kimlik_api_key_list, KimlikSAMLConfigForm as kimlik_saml_config_form, KimlikSAMLConfigList as kimlik_saml_config_list, KimlikUserList as kimlik_user_list };
