import { SubFormField } from '@dvn/core/doldurma/src/fields/sub-form';
import { TextField } from '@dvn/core/doldurma/src/fields/text';
import { Component, h, Host, Prop, State } from '@stencil/core';
import { DataTransferField } from '@dvn/core/doldurma/src/fields/query-include/data-transfer-field';
import { MultipleChoiceField, MultipleChoiceFieldOption } from '@dvn/core/doldurma/src/fields/multiple-choice';
function generateBase64ForAPIKey(createAPIKeyResponse) {
  return btoa(`${createAPIKeyResponse.keyId}:${createAPIKeyResponse.key}`);
}
export class KimlikApiKeyForm {
  constructor() {
    this.predefinedScopes = [];
    this.allowCustomScopes = true;
    this.onSubmitForm = (event) => {
      const { values } = event.detail;
      const { name, predefinedScopes = [], scopes } = values;
      const body = {
        name,
        scopes: [...predefinedScopes, ...(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, _b;
    const { allowCustomScopes, isPending, item, createAPIKeyResponse, predefinedScopes } = this;
    // separate selected custom scopes
    const customScopeValue = (_a = item === null || item === void 0 ? void 0 : item.scopes) === null || _a === void 0 ? void 0 : _a.filter(scope => !predefinedScopes.some(ps => ps.value === scope)).map(scope => ({ value: scope }));
    // separate selected predefined scopes
    const predefinedScopeValue = (_b = item === null || item === void 0 ? void 0 : item.scopes) === null || _b === void 0 ? void 0 : _b.filter(scope => predefinedScopes.some(ps => ps.value === scope));
    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 MultipleChoiceField('predefinedScopes', 'Scopes', predefinedScopes.map(ps => new MultipleChoiceFieldOption(ps.label, ps.value))).setVisibility(predefinedScopes.length > 0)
            .setValue(predefinedScopeValue),
          new SubFormField('scopes', 'Custom Scopes', [
            new TextField('value', '', 'Scope name or URI')
              .require(),
          ]).setMaxCount(10)
            .setVisibility(allowCustomScopes)
            .setValue(customScopeValue),
        ], onSubmit: this.onSubmitForm, submitButtonLabel: item ? 'Update' : 'Create', progressing: isPending })));
  }
  static get is() { return "kimlik-api-key-form"; }
  static get properties() { return {
    "apiKimlik": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "KimlikApi",
        "resolved": "KimlikApi",
        "references": {
          "KimlikApi": {
            "location": "import",
            "path": "@dvn/kimlik/api/kimlik-api"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "onChange": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "() => void",
        "resolved": "() => void",
        "references": {}
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "item": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "ApiKey",
        "resolved": "ApiKey",
        "references": {
          "ApiKey": {
            "location": "import",
            "path": "@dvn/kimlik/api/models/api-key"
          }
        }
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "predefinedScopes": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "{ label: string, value: string }[]",
        "resolved": "{ label: string; value: string; }[]",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "defaultValue": "[]"
    },
    "allowCustomScopes": {
      "type": "boolean",
      "mutable": false,
      "complexType": {
        "original": "boolean",
        "resolved": "boolean",
        "references": {}
      },
      "required": false,
      "optional": true,
      "docs": {
        "tags": [],
        "text": ""
      },
      "attribute": "allow-custom-scopes",
      "reflect": false,
      "defaultValue": "true"
    }
  }; }
  static get states() { return {
    "error": {},
    "isPending": {},
    "createAPIKeyResponse": {}
  }; }
}
