import { r as registerInstance, h, H as Host } from './index-b7735e0d.js';
import { D as DvnDataAdapter } from './DvnDataAdapter-536a3258.js';
import { D as DataTransferField } from './data-transfer-field-918730a3.js';
import { S as SingleChoiceField } from './index-80ec23ef.js';
import { T as TextField } from './index-403101cb.js';
import './index-7b119e61.js';
import { L as ListFetchState } from './list-fetch-state-d8c2f8ef.js';
import { D as DateField } from './date-ce777316.js';
import { S as SubFormField } from './index-4c39b6a6.js';
import { C as ConcealerConditional, E as Equal } from './Equal-8818d86d.js';
import { B as BooleanField } from './index-a1075948.js';
import { M as ModifierTrimmer } from './ModifierTrimmer-2f77f917.js';
import { V as ValidatorRegex, R as RawDataField } from './ValidatorRegex-20b5a564.js';
import { D as DataModel } from './data-model-f7ccf826.js';
import './BaseField-461b6d0c.js';
import './InterceptorHandler-6474bcf4.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 },
  };
}

let DamgaDomainForm = class {
  constructor(hostRef) {
    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 (h(Host, null, h("doldurma-form", { fields: [
        new DataTransferField('_id')
          .setValue(item === null || item === void 0 ? void 0 : item._id),
        new TextField('domain', 'Domain')
          .setValue(values.domain)
          .require(),
        new SingleChoiceField('loadBalancer', 'Load Balancer', [], '', 'select')
          .setDataProvider(new DvnDataProviderLoadBalancers(this.apiDamga))
          .setDataAdapter(new DvnDataAdapter('name', '_id'))
          .setValue(values.loadBalancer)
          .require(),
      ], onSubmit: this.onSubmitForm, submitButtonLabel: item ? 'Update' : 'Create', progressing: isPending, formErrors: formErrors })));
  }
};

let DamgaDomainList = 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.apiDamga.getDomains().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: 'domain' },
          { fieldId: '_created' },
        ]
      }, fields: [
        new TextField('domain', 'Domain').setInputType('url'),
        new 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,
  };
}

let DamgaLoadBalancerForm = class {
  constructor(hostRef) {
    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 (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(values.name)
          .require(),
        new SubFormField('listeners', 'Listeners', [
          new SingleChoiceField('targetGroup', 'Target Group', [], '', 'select')
            .setDataProvider(this.dataProviderTargetGroups)
            .setDataAdapter(new DvnDataAdapter('name', '_id'))
            .require(),
          new SubFormField('rules', 'Rules', [
            new 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 SubFormField('hostValue', '', [
              new TextField('value', '', 'Host value (e.g. devingen.io, khanguru.com)')
                .require(),
            ]).setMaxCount(5)
              .setSeparated(false)
              .addInterceptor('onFormChange', new ConcealerConditional(new Equal('type', 'host')))
              .setVisibility(false),
            new SubFormField('pathValue', '', [
              new TextField('value', '', 'Path value (e.g. /, /en*, /api*)')
                .require(),
            ]).setMaxCount(5)
              .addInterceptor('onFormChange', new ConcealerConditional(new Equal('type', 'path')))
              .setVisibility(false),
            new SubFormField('headerValue', '', [
              new TextField('name', '', 'Header Name (e.g. Authorization, Content-Type)')
                .require(),
              new SubFormField('values', '', [
                new TextField('value', '', 'Header Value')
                  .require(),
              ]).setMaxCount(5)
            ]).setMaxCount(5)
              .setVisibility(false)
              .addInterceptor('onFormChange', new ConcealerConditional(new Equal('type', 'header'))),
            new SubFormField('cookieValue', '', [
              new TextField('name', '', 'Cookie Name')
                .require(),
              new SubFormField('values', '', [
                new TextField('value', '', 'Cookie Value')
                  .require(),
              ]).setMaxCount(5)
            ]).setMaxCount(5)
              .setVisibility(false)
              .addInterceptor('onFormChange', new ConcealerConditional(new Equal('type', 'cookie'))),
          ]).setMaxCount(5),
        ])
          .setMinCount(0)
          .setMaxCount(5)
          .setValue(values.listeners),
        new SingleChoiceField('defaultTargetGroup', 'Default Listener Target', [], '', 'select')
          .setDataProvider(this.dataProviderTargetGroups)
          .setDataAdapter(new DvnDataAdapter('name', '_id'))
          .setValue(values.defaultTargetGroup)
          .require(),
      ], onSubmit: this.onSubmitForm, submitButtonLabel: item ? 'Update' : 'Create', progressing: isPending })));
  }
};

let DamgaLoadBalancerList = 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.apiDamga.getLoadBalancers().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' },
        ]
      }, fields: [
        new TextField('name', 'Name'),
        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 domainRegex = '(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]';
let DamgaTargetGroupForm = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.onSubmitForm = (event) => {
      const { values } = event.detail;
      const body = {
        type: 'url',
        targets: [{ value: values.target }],
        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 (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 TextField('target', 'Target', '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())
          .setValue(item === null || item === void 0 ? void 0 : item.targets[0].value)
          .require(),
        new 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 BooleanField('useTLS', 'Use TLS', 'Uses **https** instead of **http** while accessing the target.').setValue(item === null || item === void 0 ? void 0 : item.useTLS),
        new TextField('prefix', 'Prefix')
          .setValue(item === null || item === void 0 ? void 0 : item.prefix),
      ], onSubmit: this.onSubmitForm, submitButtonLabel: item ? 'Update' : 'Create', progressing: isPending, formErrors: formErrors })));
  }
};

let DamgaTargetGroupList = 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.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.decode(Object.assign(Object.assign({}, item), { target: item.targets[0].value })))).sort((a, b) => a.name.localeCompare(b.name));
    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: 'target' },
          { fieldId: '_created' },
        ],
        columns: {
          _created: {
            width: 150
          }
        }
      }, fields: [
        new TextField('name', 'Name'),
        new RawDataField('target', 'Target').setTrimStringQuotes(true),
        new DateField('_created', 'Creation Date'),
      ], items: modifiedList, isEndReached: list.isEndReached(), isProgressing: list.isPending, error: list.error ? 'Fetching list failed' : undefined, onRetry: () => this.fetchList(), scrollToFit: true })));
  }
};

export { DamgaDomainForm as damga_domain_form, DamgaDomainList as damga_domain_list, DamgaLoadBalancerForm as damga_load_balancer_form, DamgaLoadBalancerList as damga_load_balancer_list, DamgaTargetGroupForm as damga_target_group_form, DamgaTargetGroupList as damga_target_group_list };
