'use strict';

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

const index$2 = require('./index-1141a245.js');
const index$3 = require('./index-f41ad23a.js');
const index = require('./index-61f9621a.js');
const ModifierTrimmer = require('./ModifierTrimmer-1463d100.js');
const ValidatorLength = require('./ValidatorLength-06e5c6f8.js');
const dataTransferField = require('./data-transfer-field-e8417d5f.js');
const index$1 = require('./index-9d3d3d15.js');
const formViewConfig = require('./form-view-config-36569bb4.js');
const viewConfig = require('./view-config-7972654b.js');
const actions = require('./actions-d7eabd95.js');
require('./index-2eea69a0.js');
const date = require('./date-a24d7714.js');
const dataModel = require('./data-model-9afb7f54.js');
require('./state-tunnel-786a62ce.js');
require('./FieldGenerator-279a646b.js');
require('./BaseField-381327a9.js');
require('./InterceptorHandler-09a1e84b.js');
require('./table-config-8b14c7d3.js');
require('./FieldModelGenerator-1900d81a.js');
require('./reference-field-1239b0c3.js');
require('./index-0783d14f.js');
require('./index-e8e4d80b.js');
require('./index-9fd84b93.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 actions.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.DataModel.decode({
    _id: 'devingen-workspaces',
    base: 'devingen-dev',
    fields: [
      new date.DateField('_created', 'Created')
        .setDataType(date.DateDataType.Unix)
        .setDateFormat('DD MMM YYYY HH:mm'),
      new index.TextField('name', 'Name'),
    ],
    name: 'devingen-workspaces',
  }),
};

const ID$1 = 'new-product-form';
const config$1 = (apiDevingen) => formViewConfig.FormViewConfig.decode({
  _id: ID$1,
  base: 'devingen-dev',
  title: 'New product',
  table: dataConfigs['devingen-workspaces'],
  type: viewConfig.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.DataTransferField('workspaceId'),
      },
      {
        field: new index.TextField('name', 'Name').addInterceptor('onSubmit', new ValidatorLength.ValidatorLength(2, 32))
          .addInterceptor('onSubmit', new ModifierTrimmer.ModifierTrimmer())
          .require(),
      },
      {
        field: new index$1.SingleChoiceField('type', 'Product Type', [
          new index$1.SingleChoiceFieldOption('Damga', 'damga', undefined, 'Load balancer and SSL certificate service.'),
          new index$1.SingleChoiceFieldOption('Kimlik', 'kimlik', undefined, 'User and authentication management system.'),
          new index$1.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 actions.InvalidationAction('', ''),
          ],
          navigation: {
            type: 'navigation',
            direction: 'back'
          }
        });
      }).catch(() => {
        reject(['Unexpected error']);
      });
    });
  }
}

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

const DevingenHomePage = class {
  constructor(hostRef) {
    index$2.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 (index$2.h("dvn-dialog", { shown: true, onDismiss: () => {
          this.showEditWorkspaceForm = false;
          this.selectedWorkspace = undefined;
        } }, index$2.h("doldurma-form", { fields: [
          new index.TextField('name', 'Name').addInterceptor('onSubmit', new ValidatorLength.ValidatorLength(2, 32))
            .addInterceptor('onSubmit', new ModifierTrimmer.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 (index$2.h("dvn-dialog", { shown: true, onDismiss: () => {
          this.showDeleteConfirmation = false;
          this.deleteError = undefined;
        }, title: "Deletion" }, index$2.h("p", null, "Are you sure to delete this product? This action cannot be undone."), this.deleteError &&
        index$2.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.'), index$2.h("div", { slot: "actions" }, index$2.h("dvn-button", { view: "flat", onClick: () => {
          this.showDeleteConfirmation = false;
          this.deleteError = undefined;
        } }, "Cancel"), index$2.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 (index$2.h("div", { class: "d-flex justify-content-center pt-3" }, index$2.h("dvn-progress", { indefinite: true })));
    }
    return (index$2.h(index$2.Host, null, index$2.h("div", { class: "container" }, index$2.h("div", { class: "row" }, workspaceOwnerships.map(workspaceOwnership => {
      const { workspace } = workspaceOwnership;
      return (index$2.h("div", { class: "col-sm-12" }, index$2.h("div", { class: "d-flex align-items-center" }, index$2.h("h2", { class: "mt-3" }, workspace.name), index$2.h("dvn-icon-button", { iconName: "uil uil-cog", scale: "small", view: "flat", onClick: () => {
          this.selectedWorkspace = workspace;
          this.showEditWorkspaceForm = true;
        } })), index$2.h("div", { class: "row" }, products.filter(product => product.workspace._id === workspace._id).map(product => (index$2.h("div", { class: "col-sm-12 col-md-4 mb-3" }, index$2.h("stencil-route-link", { url: `/products/${product._id}` }, index$2.h("dvn-card", { bodyLeaned: true, elevation: 0, leaned: true, selectable: true, tint: "primary" }, index$2.h("devingen-product-card", { product: product })))))), index$2.h("div", { class: "col-sm-12 col-md-4" }, index$2.h("dvn-card", { bodyLeaned: true, elevation: 0, leaned: true, selectable: true, tint: "primary" }, index$2.h("devingen-product-card", { onClick: () => {
          this.showCreateProductForm = true;
          this.selectedWorkspaceToCreateProduct = workspace._id;
        } }))))));
    })), index$2.h("div", { class: "row" }, index$2.h("div", { class: "col-sm-12 col-md-4 mt-3 pt-3" }, index$2.h("dvn-button", { leaned: true, onClick: () => this.showCreateWorkspaceForm = true, view: "flat" }, index$2.h("dvn-icon", { iconName: `uil uil-plus` }), "Add new workspace")))), showCreateWorkspaceForm &&
      index$2.h("dvn-dialog", { raw: true, shown: true, onDismiss: () => this.showCreateWorkspaceForm = false }, index$2.h("dvn-app-view-form-view", { view: config(this.apiDevingen) })), showCreateProductForm &&
      index$2.h("dvn-dialog", { raw: true, shown: true, onDismiss: () => this.showCreateProductForm = false }, index$2.h("dvn-app-view-form-view", { view: config$1(this.apiDevingen), params: {
          workspaceId: selectedWorkspaceToCreateProduct,
          type: 'damga',
        } })), this.renderEditWorkspaceForm(), this.renderDeleteWorkspaceConfirmation()));
  }
};
index$3.injectNotifier(DevingenHomePage);

exports.devingen_home_page = DevingenHomePage;
