'use strict';

const index$1 = require('./index-b1edd71d.js');
const nested = require('./nested-8980065f.js');
const dataTransferField = require('./data-transfer-field-0ce05c1a.js');
const index = require('./index-a77c3004.js');
const appConfig = require('./app-config-e62f5843.js');
const filter = require('./filter-d5040f65.js');
const tableListViewConfig = require('./table-list-view-config-9651a6bc.js');
const viewConfig$1 = require('./view-config-c409ff28.js');
require('./index-42baafa9.js');
const date = require('./date-25b104f6.js');
const dataModel = require('./data-model-c51de090.js');
const tableConfig = require('./table-config-be88299b.js');
const services = require('./services-895a8d1d.js');
const formViewConfig = require('./form-view-config-36f31520.js');
const actions = require('./actions-d7eabd95.js');
const index$2 = require('./index-521d07b9.js');

const damgaSpace = tableConfig.Space.decode({
  _id: 'asdqweasd',
  _created: new Date(),
  _updated: new Date(),
  name: 'Asdqweasd',
});
const dataConfigs = {
  'damga-domains': dataModel.DataModel.decode({
    _id: 'damga-domains',
    base: services.prod.base,
    fields: [
      new date.DateField('_created', 'Created')
        .setDataType(date.DateDataType.Unix)
        .setDateFormat('DD MMM YYYY HH:mm'),
      new index.TextField('domain', 'Domain').setInputType('url'),
    ],
    name: 'damga-domains',
    space: damgaSpace,
  }),
};

class FormHandlerCreateDomain {
  constructor(apiDamga, sourceViewId) {
    this.sourceViewId = sourceViewId;
    this.api = apiDamga;
  }
  onSubmit(event) {
    const { values: { domain, overrideHost, productId, target, useTLS } } = event.detail;
    return new Promise((resolve, reject) => {
      const errorHandler = error => {
        if (error.data && error.data.message === 'domain-exists-with-same-address') {
          reject(['Domain already exists.']);
          return;
        }
        reject(['Unexpected error']);
      };
      this.api.createDomain({
        domain,
        productId,
        target: {
          type: 'proxy',
          value: target,
          overrideHost,
          useTLS,
        }
      }).then(() => {
        resolve({
          events: [
            new actions.InvalidationAction(this.sourceViewId, 'table-list-view-domain'),
          ],
          navigation: {
            type: 'navigation',
            direction: 'back'
          }
        });
      }).catch(errorHandler);
    });
  }
}

const ID$4 = 'new-domain-and-target-form';
const domainRegex$1 = '(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\\.)+[a-z0-9][a-z0-9-]{0,61}[a-z0-9]';
const config$3 = (apiDamga) => formViewConfig.FormViewConfig.decode({
  _id: ID$4,
  base: 'devingen-dev',
  title: 'New domain',
  space: damgaSpace,
  table: tableListViewConfig.dataConfigs['damga-domains'],
  type: viewConfig$1.AppViewType.FormView,
  handler: new FormHandlerCreateDomain(apiDamga, ID$4),
  ui: {
    fields: [
      // this field is passed by the parameters. this is a data holder field to pass the data to form handler
      {
        field: new dataTransferField.DataTransferField('productId'),
      },
      {
        field: new index.TextField('domain', 'Domain', 'acme.co', 'SSL certificate will be generated for this domain.').addInterceptor('onBlur', new tableListViewConfig.ValidatorRegex(domainRegex$1, 'Not a valid domain.'))
          .addInterceptor('onSubmit', new formViewConfig.ModifierTrimmer())
          .require(),
      },
      {
        field: new index.TextField('target', 'Target', 'acme.co or 1.2.3.4:5678', 'Traffic will be forwarded to this address.').addInterceptor('onBlur', new tableListViewConfig.ValidatorRegex(domainRegex$1, 'Not a valid domain or address.'))
          .addInterceptor('onSubmit', new formViewConfig.ModifierTrimmer())
          .require(),
      },
      {
        field: new index$1.BooleanField('overrideHost', 'Override Host', 'Overrides the target host with domain while accessing the target.'),
      },
      {
        field: new index$1.BooleanField('useTLS', 'Use TLS', 'Uses **https** instead of **http** while accessing the target.'),
      }
    ],
  },
  params: {
    overrideHost: {
      required: true,
      value: true,
    },
    useTLS: {
      required: true,
      value: false,
    },
  },
});

class FormHandlerUpdateDomain {
  constructor(apiDamga, sourceViewId) {
    this.sourceViewId = sourceViewId;
    this.api = apiDamga;
  }
  onSubmit(event) {
    const { values: { domainId, overrideHost, target, useTLS } } = event.detail;
    return new Promise((resolve, reject) => {
      this.api.updateDomain(domainId, {
        target: {
          type: 'proxy',
          value: target,
          overrideHost,
          useTLS,
        }
      }).then(() => {
        resolve({
          events: [
            new actions.InvalidationAction(this.sourceViewId, 'table-list-view-domain'),
          ],
          navigation: {
            type: 'navigation',
            direction: 'back'
          }
        });
      }).catch(() => {
        reject(['Unexpected error']);
      });
    });
  }
}

const ID$3 = 'update-domain-and-target-form';
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 config$2 = (apiDamga) => formViewConfig.FormViewConfig.decode({
  _id: ID$3,
  base: 'devingen-dev',
  title: 'Update domain',
  space: damgaSpace,
  table: tableListViewConfig.dataConfigs['damga-domains'],
  type: viewConfig$1.AppViewType.FormView,
  handler: new FormHandlerUpdateDomain(apiDamga, ID$3),
  ui: {
    fields: [
      // this field is passed by the parameters. this is a data holder field to pass the data to form handler
      {
        field: new dataTransferField.DataTransferField('domainId'),
      },
      {
        field: new index.TextField('domain', 'Domain').disable()
          .require(),
      },
      {
        field: new index.TextField('target', 'Target', 'acme.co or 1.2.3.4:5678', 'Traffic will be forwarded to this address.').addInterceptor('onBlur', new tableListViewConfig.ValidatorRegex(domainRegex, 'Not a valid domain or address.'))
          .addInterceptor('onSubmit', new formViewConfig.ModifierTrimmer())
          .require(),
      },
      {
        field: new index$1.BooleanField('overrideHost', 'Override Host', 'Overrides the target host with domain while accessing the target.'),
      },
      {
        field: new index$1.BooleanField('useTLS', 'Use TLS', 'Uses **https** instead of **http** while accessing the target.'),
      }
    ],
  },
  params: {
    domainId: {
      required: true,
    },
    domain: {
      required: true,
    },
    target: {
      required: true,
    },
    overrideHost: {
      required: true,
    },
    useTLS: {
      required: true,
    },
  },
});

class FormHandlerMoveDomain {
  constructor(apiDamga, sourceViewId) {
    this.sourceViewId = sourceViewId;
    this.api = apiDamga;
  }
  onSubmit(event) {
    const { values: { domainId, targetProductId } } = event.detail;
    return new Promise((resolve, reject) => {
      this.api.moveDomain(domainId, {
        productId: targetProductId,
      }).then(() => {
        resolve({
          events: [
            new actions.InvalidationAction(this.sourceViewId, 'table-list-view-domain'),
          ],
          navigation: {
            type: 'navigation',
            direction: 'back'
          }
        });
      }).catch(() => {
        reject(['Unexpected error']);
      });
    });
  }
}

const ID$2 = 'form-view-domain-move';
const config$1 = (apiDamga, products, workspaceOwnerships) => formViewConfig.FormViewConfig.decode({
  _id: ID$2,
  base: 'devingen-dev',
  title: 'Move domain',
  space: damgaSpace,
  table: tableListViewConfig.dataConfigs['damga-domains'],
  type: viewConfig$1.AppViewType.FormView,
  handler: new FormHandlerMoveDomain(apiDamga, ID$2),
  ui: {
    fields: [
      // this field is passed by the parameters. this is a data holder field to pass the data to form handler
      {
        field: new dataTransferField.DataTransferField('domainId'),
      },
      {
        field: new index$2.SingleChoiceField('targetProductId', 'Select product to move this domain', products
          .filter(p => p.type === 'damga')
          .map(product => (new index$2.SingleChoiceFieldOption(product.name, product._id, 'primary', workspaceOwnerships.find(w => w.workspace._id === product.workspace._id).workspace.name))), '', 'radioCard').setDataAdapter(new tableListViewConfig.DvnDataAdapter('name', '_id'))
          .require(),
      },
    ],
    i18n: {
      submit: 'Move Domain'
    }
  },
  params: {
    domainId: {
      required: true,
    },
    domain: {
      required: true,
    },
    target: {
      required: true,
    },
    overrideHost: {
      required: true,
    },
    useTLS: {
      required: true,
    },
  },
});

class FormHandlerDeleteDomain {
  constructor(apiDamga, sourceViewId) {
    this.sourceViewId = sourceViewId;
    this.api = apiDamga;
  }
  onSubmit(event) {
    const { values: { domainId } } = event.detail;
    return new Promise((resolve, reject) => {
      this.api.deleteDomain(domainId).then(() => {
        resolve({
          events: [
            new actions.InvalidationAction(this.sourceViewId, 'table-list-view-domain'),
          ],
          navigation: {
            type: 'navigation',
            direction: 'back'
          }
        });
      }).catch(() => {
        reject(['Unexpected error']);
      });
    });
  }
}

const ID$1 = 'form-view-domain-delete';
const config = (apiDamga) => formViewConfig.FormViewConfig.decode({
  _id: ID$1,
  base: 'devingen-dev',
  title: 'Are you sure to delete the domain?',
  space: damgaSpace,
  table: tableListViewConfig.dataConfigs['damga-domains'],
  type: viewConfig$1.AppViewType.FormView,
  handler: new FormHandlerDeleteDomain(apiDamga, ID$1),
  ui: {
    fields: [
      // this field is passed by the parameters. this is a data holder field to pass the data to form handler
      {
        field: new dataTransferField.DataTransferField('domainId'),
      },
    ],
    i18n: {
      submit: 'Delete Domain',
    }
  },
  params: {
    domainId: {
      required: true,
    },
    domain: {
      required: true,
    },
    target: {
      required: true,
    },
    overrideHost: {
      required: true,
    },
    useTLS: {
      required: true,
    },
  },
});

const ID = 'table-list-view-domain';
const viewConfig = (productId) => tableListViewConfig.TableListViewConfig.decode({
  _id: ID,
  type: viewConfig$1.AppViewType.ListViewTable,
  base: 'devingen-dev',
  title: 'Domains',
  space: damgaSpace,
  table: dataConfigs['damga-domains'],
  query: {
    fields: [
      new dataTransferField.DataTransferField('_created'),
      new dataTransferField.DataTransferField('domain'),
      new dataTransferField.DataTransferField('target'),
    ],
    filter: {
      comparison: filter.Comparison.EqMongoOID,
      id: 'product._id',
      value: productId,
    },
    sort: [{ id: 'domain', order: 1 }]
  },
  ui: tableListViewConfig.TableListViewConfig.decode({
    header: {
      actions: [{
          ui: {
            name: 'new-domain-and-target',
            buttonType: 'button',
            label: 'Add New'
          },
          data: {
            type: 'navigation',
            direction: 'forward',
            placement: appConfig.ViewPlacement.Dialog,
            viewId: ID$4
          }
        }],
    },
    main: {
      actions: [
        {
          ui: {
            name: 'edit',
            label: 'Edit',
            buttonType: 'icon-button',
            iconName: 'uil uil-pen',
            view: 'flat'
          },
          data: {
            type: 'navigation',
            direction: 'forward',
            placement: appConfig.ViewPlacement.Dialog,
            viewId: ID$3,
            params: {
              conversionConfig: {
                'item._id': 'domainId',
                'item.domain': 'domain',
                'item.target.value': 'target',
                'item.target.overrideHost': 'overrideHost',
                'item.target.useTLS': 'useTLS',
              },
            }
          }
        },
        {
          ui: {
            name: 'move',
            label: 'Move to another product',
            buttonType: 'icon-button',
            iconName: 'uil uil-exchange-alt',
            view: 'flat'
          },
          data: {
            type: 'navigation',
            direction: 'forward',
            placement: appConfig.ViewPlacement.Dialog,
            viewId: ID$2,
            params: {
              conversionConfig: {
                'item._id': 'domainId',
              },
            }
          }
        },
        {
          ui: {
            name: 'delete',
            label: 'Delete domain',
            buttonType: 'icon-button',
            iconName: 'uil uil-trash',
            view: 'flat',
            tint: 'danger',
          },
          data: {
            type: 'navigation',
            direction: 'forward',
            placement: appConfig.ViewPlacement.Dialog,
            viewId: ID$1,
            params: {
              conversionConfig: {
                'item._id': 'domainId',
              },
            }
          }
        },
      ],
      fields: [
        { fieldId: 'domain' },
        {
          fieldId: 'target.value',
          fieldDisplay: new nested.NestedField('target.value', new index.TextField('value', 'Target')),
        },
        {
          fieldId: 'target.overrideHost',
          fieldDisplay: new nested.NestedField('target.overrideHost', new index$1.BooleanField('overrideHost', 'Override Host')),
        },
        {
          fieldId: 'target.useTLS',
          fieldDisplay: new nested.NestedField('target.useTLS', new index$1.BooleanField('useTLS', 'Use TLS')),
        },
        {
          fieldId: 'domain',
          fieldDisplay: new index.TextField('domain', 'DNS Record'),
          componentTag: 'devingen-product-damga-domain-table-list-dns-record',
        },
      ],
      columns: {
        'target.overrideHost': {
          width: 150,
        },
        'target.useTLS': {
          width: 150,
        },
      },
    },
  }),
});

exports.ID = ID;
exports.ID$1 = ID$4;
exports.ID$2 = ID$3;
exports.ID$3 = ID$2;
exports.ID$4 = ID$1;
exports.config = config$3;
exports.config$1 = config$2;
exports.config$2 = config$1;
exports.config$3 = config;
exports.damgaSpace = damgaSpace;
exports.viewConfig = viewConfig;
