import { r as registerInstance, h, H as Host } from './index-ecdfb761.js';
import { i as injectNotifier } from './index-1e6a7311.js';
import { T as TextField } from './index-150b6a59.js';
import { M as ModifierTrimmer } from './ModifierTrimmer-2f77f917.js';
import { V as ValidatorLength } from './ValidatorLength-f56a7c14.js';
import { D as DataTransferField } from './data-transfer-field-2f305919.js';
import { S as SingleChoiceField, a as SingleChoiceFieldOption } from './index-23baeeef.js';
import { F as FormViewConfig } from './form-view-config-db7fef80.js';
import { A as AppViewType } from './view-config-2fc2ba10.js';
import { I as InvalidationAction } from './actions-b9a0f808.js';
import './index-61dcd269.js';
import { D as DateField, a as DateDataType } from './date-1bc489bd.js';
import { D as DataModel } from './data-model-f7ccf826.js';
import './state-tunnel-04c0b67a.js';
import './FieldGenerator-3ae403b2.js';
import './BaseField-0b01dc2c.js';
import './InterceptorHandler-6474bcf4.js';
import './table-config-3820fb34.js';
import './FieldModelGenerator-03c7516c.js';
import './reference-field-a5b414d1.js';
import './index-4e451db4.js';
import './index-32d8b974.js';
import './index-09efdc01.js';

class FormHandlerCreateProduct {
  constructor(apiDevingen) {
    this.api = apiDevingen;
  }
  onSubmit(event) {
    const { values: { name, workspaceId, type } } = event.detail;
    return new Promise((resolve, reject) => {
      this.api.createProduct({ name, workspace: { _id: workspaceId }, type }).then(() => {
        resolve({
          events: [
            new InvalidationAction('', ''),
          ],
          navigation: {
            type: 'navigation',
            direction: 'back'
          }
        });
      }).catch((error) => {
        var _a;
        reject(((_a = error.data) === null || _a === void 0 ? void 0 : _a.error) ? [error.data.error] : ['Unexpected error']);
      });
    });
  }
}

const dataConfigs = {
  'devingen-workspaces': DataModel.decode({
    _id: 'devingen-workspaces',
    base: 'devingen-dev',
    fields: [
      new DateField('_created', 'Created')
        .setDataType(DateDataType.Unix)
        .setDateFormat('DD MMM YYYY HH:mm'),
      new TextField('name', 'Name'),
    ],
    name: 'devingen-workspaces',
  }),
};

const ID$1 = 'new-product-form';
const config$1 = (apiDevingen) => FormViewConfig.decode({
  _id: ID$1,
  base: 'devingen-dev',
  title: 'New product',
  table: dataConfigs['devingen-workspaces'],
  type: AppViewType.FormView,
  handler: new FormHandlerCreateProduct(apiDevingen),
  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('workspaceId'),
      },
      {
        field: new TextField('name', 'Name').addInterceptor('onSubmit', new ValidatorLength(2, 32))
          .addInterceptor('onSubmit', new ModifierTrimmer())
          .require(),
      },
      {
        field: new SingleChoiceField('type', 'Product Type', [
          new SingleChoiceFieldOption('Damga', 'damga', undefined, 'Load balancer and SSL certificate service.'),
          new SingleChoiceFieldOption('Kimlik', 'kimlik', undefined, 'User and authentication management system.'),
          new SingleChoiceFieldOption('Database', 'taban', undefined, 'Document database.'),
          // new SingleChoiceFieldOption('Sepet', 'sepet', 'warning', 'CDN service for serving files.'), // yes, coming soon :)
        ], '', 'radioCard').require(),
      },
    ],
  },
});

class FormHandlerCreateWorkspace {
  constructor(apiDevingen) {
    this.api = apiDevingen;
  }
  onSubmit(event) {
    const { values: { name } } = event.detail;
    return new Promise((resolve, reject) => {
      this.api.createWorkspace(name).then(() => {
        resolve({
          events: [
            new InvalidationAction('', ''),
          ],
          navigation: {
            type: 'navigation',
            direction: 'back'
          }
        });
      }).catch(() => {
        reject(['Unexpected error']);
      });
    });
  }
}

const ID = 'new-workspace-form';
const config = (apiDevingen) => FormViewConfig.decode({
  _id: ID,
  base: 'devingen-dev',
  title: 'New workspace',
  table: dataConfigs['devingen-workspaces'],
  type: AppViewType.FormView,
  handler: new FormHandlerCreateWorkspace(apiDevingen),
  ui: {
    fields: [
      {
        field: new TextField('name', 'Name').addInterceptor('onSubmit', new ValidatorLength(2, 32))
          .addInterceptor('onSubmit', new ModifierTrimmer())
          .require(),
      },
    ],
  },
});

const DevingenHomePage = class {
  constructor(hostRef) {
    registerInstance(this, hostRef);
    this.showCreateWorkspaceForm = false;
    this.showCreateProductForm = false;
    this.showEditWorkspaceForm = false;
    this.showDeleteConfirmation = false;
    this.renderEditWorkspaceForm = () => {
      var _a;
      if (!this.showEditWorkspaceForm) {
        return null;
      }
      return (h("dvn-dialog", { shown: true, onDismiss: () => {
          this.showEditWorkspaceForm = false;
          this.selectedWorkspace = undefined;
        } }, h("doldurma-form", { fields: [
          new TextField('name', 'Name').addInterceptor('onSubmit', new ValidatorLength(2, 32))
            .addInterceptor('onSubmit', new ModifierTrimmer())
            .setValue((_a = this.selectedWorkspace) === null || _a === void 0 ? void 0 : _a.name)
            .require(),
        ], onSubmit: this.onSubmitEditWorkspaceForm, submitButtonLabel: "Update", extraButtons: [{
            label: 'Delete',
            tint: 'danger',
            view: 'flat',
            onClick: () => {
              this.showDeleteConfirmation = true;
            },
          }], formErrors: this.updateError ? ['Update failed.'] : undefined })));
    };
    this.renderDeleteWorkspaceConfirmation = () => {
      var _a;
      if (!this.showDeleteConfirmation) {
        return null;
      }
      return (h("dvn-dialog", { shown: true, onDismiss: () => {
          this.showDeleteConfirmation = false;
          this.deleteError = undefined;
        }, title: "Deletion" }, h("p", null, "Are you sure to delete this product? This action cannot be undone."), this.deleteError &&
        h("p", { class: "text-danger" }, ((_a = this.deleteError.data) === null || _a === void 0 ? void 0 : _a.error) === 'workspace-has-products'
          ? 'You need to delete all products belong to this workspace before deleting it.'
          : 'Delete failed.'), h("div", { slot: "actions" }, h("dvn-button", { view: "flat", onClick: () => {
          this.showDeleteConfirmation = false;
          this.deleteError = undefined;
        } }, "Cancel"), h("dvn-button", { tint: "danger", onClick: this.onConfirmDeleteWorkspace }, "Yes, Delete"))));
    };
    this.onSubmitEditWorkspaceForm = (event) => {
      const { values } = event.detail;
      this.apiDevingen.updateWorkspace(this.selectedWorkspace._id, Object.assign(Object.assign({}, this.selectedWorkspace), { name: values.name }))
        .then(() => {
        location.reload();
      })
        .catch(error => this.updateError = error);
    };
    this.onConfirmDeleteWorkspace = () => {
      this.apiDevingen.deleteWorkspace(this.selectedWorkspace._id)
        .then(() => location.pathname = '/')
        .catch(error => this.deleteError = error);
    };
  }
  onInvalidation(_event) {
    // new workspace or product is created
    this.showCreateWorkspaceForm = false;
    this.showCreateProductForm = false;
  }
  ;
  render() {
    const { showCreateProductForm, showCreateWorkspaceForm, products, selectedWorkspaceToCreateProduct, workspaceOwnerships } = this;
    if (!workspaceOwnerships || !products) {
      return (h("div", { class: "d-flex justify-content-center pt-3" }, h("dvn-progress", { indefinite: true })));
    }
    return (h(Host, null, h("div", { class: "container" }, h("div", { class: "row" }, workspaceOwnerships.map(workspaceOwnership => {
      const { workspace } = workspaceOwnership;
      return (h("div", { class: "col-sm-12" }, h("div", { class: "d-flex align-items-center" }, h("h2", { class: "mt-3" }, workspace.name), h("dvn-icon-button", { iconName: "uil uil-cog", scale: "small", view: "flat", onClick: () => {
          this.selectedWorkspace = workspace;
          this.showEditWorkspaceForm = true;
        } })), h("div", { class: "row" }, products.filter(product => product.workspace._id === workspace._id).map(product => (h("div", { class: "col-sm-12 col-md-4 mb-3" }, h("stencil-route-link", { url: `/products/${product._id}` }, h("dvn-card", { bodyLeaned: true, elevation: 0, leaned: true, selectable: true, tint: "primary" }, h("devingen-product-card", { product: product })))))), h("div", { class: "col-sm-12 col-md-4" }, h("dvn-card", { bodyLeaned: true, elevation: 0, leaned: true, selectable: true, tint: "primary" }, h("devingen-product-card", { onClick: () => {
          this.showCreateProductForm = true;
          this.selectedWorkspaceToCreateProduct = workspace._id;
        } }))))));
    })), h("div", { class: "row" }, h("div", { class: "col-sm-12 col-md-4 mt-3 pt-3" }, h("dvn-button", { leaned: true, onClick: () => this.showCreateWorkspaceForm = true, view: "flat" }, h("dvn-icon", { iconName: `uil uil-plus` }), "Add new workspace")))), showCreateWorkspaceForm &&
      h("dvn-dialog", { raw: true, shown: true, onDismiss: () => this.showCreateWorkspaceForm = false }, h("dvn-app-view-form-view", { view: config(this.apiDevingen) })), showCreateProductForm &&
      h("dvn-dialog", { raw: true, shown: true, onDismiss: () => this.showCreateProductForm = false }, h("dvn-app-view-form-view", { view: config$1(this.apiDevingen), params: {
          workspaceId: selectedWorkspaceToCreateProduct,
          type: 'damga',
        } })), this.renderEditWorkspaceForm(), this.renderDeleteWorkspaceConfirmation()));
  }
};
injectNotifier(DevingenHomePage);

export { DevingenHomePage as devingen_home_page };
