'use strict';

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

const index = require('./index-1141a245.js');
const DvnDataAdapter = require('./DvnDataAdapter-8f89f436.js');
const dataTransferField = require('./data-transfer-field-e8417d5f.js');
const index$2 = require('./index-9d3d3d15.js');
const index$1 = require('./index-61f9621a.js');
require('./index-2eea69a0.js');
const listFetchState = require('./list-fetch-state-6f8f3bf8.js');
const date = require('./date-a24d7714.js');
const index$3 = require('./index-9fd84b93.js');
const Equal = require('./Equal-e7239026.js');
const index$4 = require('./index-e99b474f.js');
const ModifierTrimmer = require('./ModifierTrimmer-1463d100.js');
const InterceptorHandler = require('./InterceptorHandler-09a1e84b.js');
const rawData = require('./raw-data-34f1739c.js');
const dataModel = require('./data-model-01c368bc.js');
require('./BaseField-381327a9.js');
require('./FieldGenerator-279a646b.js');

class DvnDataProviderLoadBalancers {
  constructor(damgaApi) {
    this.damgaApi = damgaApi;
  }
  getInitialData() {
    return this.getData();
  }
  getData() {
    return new Promise((resolve) => {
      this.damgaApi.getLoadBalancers()
        .then(response => resolve(response.results.sort((a, b) => a.name.localeCompare(b.name))));
    });
  }
  getQuickSearchText() {
    return '';
  }
  isQuickSearchEnabled() {
    return false;
  }
  setInitialData(_data) {
  }
  setQuickSearchText(_text) {
  }
}

function convertDomainToFormValues(item) {
  var _a;
  if (!item) {
    return {};
  }
  return {
    domain: item.domain,
    loadBalancer: (_a = item.loadBalancer) === null || _a === void 0 ? void 0 : _a._id,
  };
}
function convertFormValuesToDomain(values) {
  return {
    domain: values.domain,
    loadBalancer: { _id: values.loadBalancer },
  };
}

const DamgaDomainForm = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.onSubmitForm = (event) => {
      const { values } = event.detail;
      const body = convertFormValuesToDomain(values);
      const promise = values._id
        ? this.apiDamga.updateDomain(values._id, body)
        : this.apiDamga.createDomain(body);
      this.isPending = true;
      promise.then(this.onChange)
        .catch(error => {
        var _a;
        this.formErrors = [(_a = error.data) === null || _a === void 0 ? void 0 : _a.error];
      })
        .finally(() => this.isPending = false);
    };
  }
  render() {
    const { formErrors, isPending, item } = this;
    const values = convertDomainToFormValues(item);
    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('domain', 'Domain')
          .setValue(values.domain)
          .require(),
        new index$2.SingleChoiceField('loadBalancer', 'Load Balancer', [], '', 'select')
          .setDataProvider(new DvnDataProviderLoadBalancers(this.apiDamga))
          .setDataAdapter(new DvnDataAdapter.DvnDataAdapter('name', '_id'))
          .setValue(values.loadBalancer)
          .require(),
      ], onSubmit: this.onSubmitForm, submitButtonLabel: item ? 'Update' : 'Create', progressing: isPending, formErrors: formErrors })));
  }
};

const DamgaDomainList = 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.apiDamga.getDomains().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: 'domain' },
          { fieldId: '_created' },
        ]
      }, fields: [
        new index$1.TextField('domain', 'Domain').setInputType('url'),
        new date.DateField('_created', 'Creation Date'),
      ], items: (list.data || []).sort((a, b) => a.domain.localeCompare(b.domain)), isEndReached: list.isEndReached(), isProgressing: list.isPending, error: list.error ? 'Fetching list failed' : undefined, onRetry: () => this.fetchList(), scrollToFit: true })));
  }
};

class DvnDataProviderTargetGroups {
  constructor(damgaApi) {
    this.damgaApi = damgaApi;
  }
  getInitialData() {
    return this.getData();
  }
  getData() {
    if (this.list) {
      return Promise.resolve(this.list);
    }
    return new Promise((resolve) => {
      this.damgaApi.getTargetGroups().then(response => {
        this.list = response.results.sort((a, b) => a.name.localeCompare(b.name));
        resolve(this.list);
      });
    });
  }
  getQuickSearchText() {
    return '';
  }
  isQuickSearchEnabled() {
    return false;
  }
  setInitialData(_data) {
  }
  setQuickSearchText(_text) {
  }
}

function convertLoadBalancerToFormValues(item) {
  if (!item) {
    return {};
  }
  const listeners = [...item.listeners];
  const lastListener = listeners.pop();
  const formListeners = listeners.map(listener => {
    const rules = listener.rules.map(rule => {
      const denormalisedRule = {
        type: rule.type,
      };
      switch (rule.type) {
        case 'cookie':
          denormalisedRule.cookieValue = [];
          Object.keys(rule.cookieValue).forEach(k => {
            denormalisedRule.cookieValue.push({
              name: k,
              values: rule.cookieValue[k],
            });
          });
          break;
        case 'header':
          denormalisedRule.headerValue = [];
          Object.keys(rule.headerValue).forEach(k => {
            denormalisedRule.headerValue.push({
              name: k,
              values: rule.headerValue[k],
            });
          });
          break;
        case 'host':
          denormalisedRule.hostValue = rule.hostValue.map(v => ({ value: v }));
          break;
        case 'path':
          denormalisedRule.pathValue = rule.pathValue.map(v => ({ value: v }));
          break;
      }
      return denormalisedRule;
    });
    return {
      rules,
      targetGroup: listener.forwardAction.targets[0].targetGroup._id,
    };
  });
  return {
    listeners: formListeners,
    name: item.name,
    defaultTargetGroup: lastListener.forwardAction.targets[0].targetGroup._id,
  };
}
function convertFormValuesToLoadBalancer(values) {
  var _a;
  const listeners = ((_a = values.listeners) === null || _a === void 0 ? void 0 : _a.map(listener => ({
    port: 443,
    forwardAction: {
      targets: [
        {
          weight: 1,
          targetGroup: {
            _id: listener.targetGroup,
          }
        }
      ],
    },
    rules: listener.rules.map(rule => {
      var _a;
      const normalisedRule = {
        type: rule.type,
      };
      switch (rule.type) {
        case 'cookie':
          normalisedRule.cookieValue = {};
          rule.cookieValue.forEach(v => {
            normalisedRule.cookieValue[v.name] = v.values || [''];
          });
          break;
        case 'header':
          normalisedRule.headerValue = {};
          rule.headerValue.forEach(v => {
            normalisedRule.headerValue[v.name] = v.values || [''];
          });
          break;
        case 'host':
          normalisedRule.hostValue = (_a = rule.hostValue) === null || _a === void 0 ? void 0 : _a.map(v => (v === null || v === void 0 ? void 0 : v.value) || '');
          break;
        case 'path':
          normalisedRule.pathValue = rule.pathValue.map(v => (v === null || v === void 0 ? void 0 : v.value) || '');
          break;
      }
      return normalisedRule;
    })
  }))) || [];
  listeners.push({
    port: 443,
    forwardAction: { targets: [{ weight: 1, targetGroup: { _id: values.defaultTargetGroup } }] }
  });
  return {
    name: values.name,
    listeners,
  };
}

const DamgaLoadBalancerForm = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.onSubmitForm = (event) => {
      const { values } = event.detail;
      const body = convertFormValuesToLoadBalancer(values);
      const promise = values._id
        ? this.apiDamga.updateLoadBalancer(values._id, body)
        : this.apiDamga.createLoadBalancer(body);
      this.isPending = true;
      promise.then(this.onChange)
        .finally(() => this.isPending = false);
    };
  }
  componentWillLoad() {
    this.dataProviderTargetGroups = new DvnDataProviderTargetGroups(this.apiDamga);
  }
  render() {
    const { isPending, item } = this;
    const values = convertLoadBalancerToFormValues(item);
    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(values.name)
          .require(),
        new index$3.SubFormField('listeners', 'Listeners', [
          new index$2.SingleChoiceField('targetGroup', 'Target Group', [], '', 'select')
            .setDataProvider(this.dataProviderTargetGroups)
            .setDataAdapter(new DvnDataAdapter.DvnDataAdapter('name', '_id'))
            .require(),
          new index$3.SubFormField('rules', 'Rules', [
            new index$2.SingleChoiceField('type', '', [
              { label: 'Cookie', value: 'cookie' },
              { label: 'Header', value: 'header' },
              { label: 'Host', value: 'host' },
              { label: 'Path', value: 'path' },
              // the ones below are not yet supported by the damga-proxy server
              // { label: 'Method', value: 'method' },
              // { label: 'Query Param', value: 'query' },
              // { label: 'Source IP', value: 'source-ip' },
            ], '', 'select', 'Type')
              .require(),
            new index$3.SubFormField('hostValue', '', [
              new index$1.TextField('value', '', 'Host value (e.g. devingen.io, khanguru.com)')
                .require(),
            ]).setMaxCount(5)
              .setSeparated(false)
              .addInterceptor('onFormChange', new Equal.ConcealerConditional(new Equal.Equal('type', 'host')))
              .setVisibility(false),
            new index$3.SubFormField('pathValue', '', [
              new index$1.TextField('value', '', 'Path value (e.g. /, /en*, /api*)')
                .require(),
            ]).setMaxCount(5)
              .addInterceptor('onFormChange', new Equal.ConcealerConditional(new Equal.Equal('type', 'path')))
              .setVisibility(false),
            new index$3.SubFormField('headerValue', '', [
              new index$1.TextField('name', '', 'Header Name (e.g. Authorization, Content-Type)')
                .require(),
              new index$3.SubFormField('values', '', [
                new index$1.TextField('value', '', 'Header Value')
                  .require(),
              ]).setMaxCount(5)
            ]).setMaxCount(5)
              .setVisibility(false)
              .addInterceptor('onFormChange', new Equal.ConcealerConditional(new Equal.Equal('type', 'header'))),
            new index$3.SubFormField('cookieValue', '', [
              new index$1.TextField('name', '', 'Cookie Name')
                .require(),
              new index$3.SubFormField('values', '', [
                new index$1.TextField('value', '', 'Cookie Value')
                  .require(),
              ]).setMaxCount(5)
            ]).setMaxCount(5)
              .setVisibility(false)
              .addInterceptor('onFormChange', new Equal.ConcealerConditional(new Equal.Equal('type', 'cookie'))),
          ]).setMaxCount(5),
        ])
          .setMinCount(0)
          .setMaxCount(10)
          .setValue(values.listeners),
        new index$2.SingleChoiceField('defaultTargetGroup', 'Default Listener Target', [], '', 'select')
          .setDataProvider(this.dataProviderTargetGroups)
          .setDataAdapter(new DvnDataAdapter.DvnDataAdapter('name', '_id'))
          .setValue(values.defaultTargetGroup)
          .require(),
      ], onSubmit: this.onSubmitForm, submitButtonLabel: item ? 'Update' : 'Create', progressing: isPending })));
  }
};

const DamgaLoadBalancerList = 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.apiDamga.getLoadBalancers().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' },
        ]
      }, fields: [
        new index$1.TextField('name', 'Name'),
        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 })));
  }
};

class ValidatorRegex extends InterceptorHandler.InterceptorConfig {
  constructor(regex, message) {
    super('validatorAlphanumericChar');
    this.regexFlags = 'gm';
    this.regex = regex;
    this.message = message;
  }
}
ValidatorRegex.id = 'validatorAlphanumericChar';
class ValidatorRegexHandler extends InterceptorHandler.InterceptorHandler {
  constructor(config) {
    super();
    this.config = config;
  }
  run(context, _, field, value) {
    if (typeof value === 'string' || value instanceof String) {
      if (!new RegExp(this.config.regex, this.config.regexFlags).test(value)) {
        const errorMessage = this.config.message || context.strings.interceptors.validatorRegex.message;
        return {
          error: errorMessage.replace('{title}', field.errorTitle || field.title),
          value,
        };
      }
    }
    return { value };
  }
}
InterceptorHandler.registerInterceptor(ValidatorRegex.id, (config) => new ValidatorRegexHandler(config));

const domainRegex = '(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]';
const DamgaTargetGroupForm = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.onSubmitForm = (event) => {
      const { values } = event.detail;
      const body = {
        type: 'url',
        targets: values.targets,
        overrideHost: !!values.overrideHost,
        useTLS: !!values.useTLS,
        name: values.name,
        prefix: values.prefix,
      };
      const promise = values._id
        ? this.apiDamga.updateTargetGroup(values._id, body)
        : this.apiDamga.createTargetGroup(body);
      this.isPending = true;
      promise.then(this.onChange)
        .catch(error => {
        var _a;
        this.formErrors = (_a = error.data) === null || _a === void 0 ? void 0 : _a.errors;
      })
        .finally(() => this.isPending = false);
    };
  }
  render() {
    const { formErrors, 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.SubFormField('targets', 'Targets', [
          new index$1.TextField('value', 'Address', 'acme.co, acme.co:5678, 1.2.3.4:5678', 'Traffic will be forwarded to this address. Should not contain protocol prefix.')
            .addInterceptor('onBlur', new ValidatorRegex(domainRegex, 'Not a valid domain or address.'))
            .addInterceptor('onSubmit', new ModifierTrimmer.ModifierTrimmer())
            .require(),
        ]).setMaxCount(5)
          .setValue(item === null || item === void 0 ? void 0 : item.targets),
        new index$4.BooleanField('overrideHost', 'Override Host', 'Overrides the target host with domain while accessing the target.').setValue(item === null || item === void 0 ? void 0 : item.overrideHost),
        new index$4.BooleanField('useTLS', 'Use TLS', 'Uses **https** instead of **http** while accessing the target.').setValue(item === null || item === void 0 ? void 0 : item.useTLS),
        new index$1.TextField('prefix', 'Prefix')
          .setValue(item === null || item === void 0 ? void 0 : item.prefix),
      ], onSubmit: this.onSubmitForm, submitButtonLabel: item ? 'Update' : 'Create', progressing: isPending, formErrors: formErrors })));
  }
};

const DamgaTargetGroupList = 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.apiDamga.getTargetGroups().catch(error => {
      this.list = list.afterFetchError(error);
    });
    if (!response)
      return;
    this.list = list.afterFetch(response, false);
  }
  render() {
    const { list } = this;
    // show the first target value as the only target value in the list
    const modifiedList = (list.data || []).map(item => (dataModel.DataModel.decode(Object.assign(Object.assign({}, item), { target: item.targets.map(target => target.value).join(', ') })))).sort((a, b) => a.name.localeCompare(b.name));
    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: 'target' },
          { fieldId: '_created' },
          { fieldId: '_id' },
        ],
        columns: {
          _created: {
            width: 150
          }
        }
      }, fields: [
        new index$1.TextField('name', 'Name'),
        new rawData.RawDataField('target', 'Target').setTrimStringQuotes(true),
        new rawData.RawDataField('_id', 'ID'),
        new date.DateField('_created', 'Creation Date'),
      ], items: modifiedList, isEndReached: list.isEndReached(), isProgressing: list.isPending, error: list.error ? 'Fetching list failed' : undefined, onRetry: () => this.fetchList(), scrollToFit: true })));
  }
};

exports.damga_domain_form = DamgaDomainForm;
exports.damga_domain_list = DamgaDomainList;
exports.damga_load_balancer_form = DamgaLoadBalancerForm;
exports.damga_load_balancer_list = DamgaLoadBalancerList;
exports.damga_target_group_form = DamgaTargetGroupForm;
exports.damga_target_group_list = DamgaTargetGroupList;
