import { TextField } from '@dvn/core/doldurma/src/fields/text';
import { ModifierTrimmer } from '@dvn/core/doldurma/src/interceptors/modifiers/ModifierTrimmer';
import { ValidatorLength } from '@dvn/core/doldurma/src/interceptors/validators/ValidatorLength';
import { Component, h, Host, Prop, State } from '@stencil/core';
import services from '../../configs/services';
import { DamgaApi } from "../../../damga/src/api/damga-api";
import { DasDamgaApi } from "../../api/das-damga-api";
export class DevingenProductPage {
  constructor() {
    this.showEditProductForm = false;
    this.showDeleteConfirmation = false;
    this.fetchProduct = async () => {
      const { id } = this.match.params;
      this.product = await this.apiDevingen.getProduct(id).catch((e) => this.error = e);
    };
    this.renderHeader = () => {
      var _a;
      return (h("div", { class: "container" },
        h("div", { class: "row" },
          h("div", { class: "col d-flex align-items-center pt-2 pb-3" },
            h("h2", { class: "m-0" }, (_a = this.product) === null || _a === void 0 ? void 0 : _a.name),
            h("dvn-icon-button", { iconName: "uil uil-cog", scale: "small", view: "flat", onClick: () => this.showEditProductForm = true })))));
    };
    this.renderEditProductForm = () => {
      if (!this.showEditProductForm) {
        return null;
      }
      return (h("dvn-dialog", { shown: true, onDismiss: () => this.showEditProductForm = false },
        h("doldurma-form", { fields: [
            new TextField('name', 'Name').addInterceptor('onSubmit', new ValidatorLength(2, 32))
              .addInterceptor('onSubmit', new ModifierTrimmer())
              .setValue(this.product.name)
              .require(),
          ], onSubmit: this.onSubmitEditProductForm, submitButtonLabel: "Update", extraButtons: [{
              label: 'Delete',
              tint: 'danger',
              view: 'flat',
              onClick: () => {
                this.showDeleteConfirmation = true;
              },
            }], formErrors: this.updateError ? ['Update failed.'] : undefined })));
    };
    this.renderDeleteProductConfirmation = () => {
      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) === 'product-has-target-groups'
            ? 'You need to delete all domains, load balancers and target groups inside the product 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.onConfirmDeleteProduct }, "Yes, Delete"))));
    };
    this.onSubmitEditProductForm = (event) => {
      const { values } = event.detail;
      this.apiDevingen.updateProduct(this.product._id, Object.assign(Object.assign({}, this.product), { name: values.name }))
        .then(() => {
        this.showEditProductForm = false;
        this.fetchProduct();
      })
        .catch(error => this.updateError = error);
    };
    this.onConfirmDeleteProduct = () => {
      this.apiDevingen.deleteProduct(this.product._id)
        .then(() => location.pathname = '/')
        .catch(error => this.deleteError = error);
    };
  }
  componentWillLoad() {
    this.fetchProduct();
  }
  render() {
    const { apiData, apiDevingen, apiKimlik, product, products, workspaceOwnerships } = this;
    if (!product) {
      return (h("div", { class: "d-flex justify-content-center pt-3" },
        h("dvn-progress", { indefinite: true })));
    }
    let Tag = `devingen-product-root-${product.type}`;
    if (product.type === 'damga') {
      return (h(Host, null,
        this.renderHeader(),
        h("damga-home", { apiEndpoint: services.damga, apiHeaders: {
            Authorization: apiKimlik.api.getDefaults().headers['Authorization']
          }, apiQueryParams: {
            productId: product._id
          }, extraTabs: [
            // {
            //   key: 'logs',
            //   label: 'Logs',
            //   render: () => <damga-domain-logs
            //     apiDamga={
            //       new DamgaApi(
            //         services.damga,
            //         { Authorization: (apiKimlik as any).api.getDefaults().headers['Authorization'] },
            //         { productId: product._id },
            //       )
            //     }
            //     apiServicesDamga={
            //       new DasDamgaApi(
            //         services.dasDamga,
            //         { Authorization: (apiKimlik as any).api.getDefaults().headers['Authorization'] },
            //         { productId: product._id },
            //       )
            //     }
            //   />
            // },
            {
              key: 'dashboard',
              label: 'Dashboard',
              render: () => h("damga-dashboard", { apiDamga: new DamgaApi(services.damga, { Authorization: apiKimlik.api.getDefaults().headers['Authorization'] }, { productId: product._id }), apiServicesDamga: new DasDamgaApi(services.dasDamga, { Authorization: apiKimlik.api.getDefaults().headers['Authorization'] }, { productId: product._id }) })
            }
          ] }),
        this.renderEditProductForm(),
        this.renderDeleteProductConfirmation()));
    }
    return (h(Host, null,
      this.renderHeader(),
      this.renderEditProductForm(),
      this.renderDeleteProductConfirmation(),
      h(Tag, { apiData: apiData, apiDevingen: apiDevingen, apiHeaders: {
          Authorization: apiKimlik.api.getDefaults().headers['Authorization']
        }, product: product, products: products, workspaceOwnerships: workspaceOwnerships })));
  }
  static get is() { return "devingen-product-page"; }
  static get properties() { return {
    "match": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "MatchResults",
        "resolved": "MatchResults",
        "references": {
          "MatchResults": {
            "location": "import",
            "path": "@stencil/router"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "apiDevingen": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "DevingenApi",
        "resolved": "DevingenApi",
        "references": {
          "DevingenApi": {
            "location": "import",
            "path": "../../api/devingen-api"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "apiData": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "DataApi",
        "resolved": "DataApi",
        "references": {
          "DataApi": {
            "location": "import",
            "path": "@dvn/core/api"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "apiKimlik": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "KimlikApi",
        "resolved": "KimlikApi",
        "references": {
          "KimlikApi": {
            "location": "import",
            "path": "@dvn/kimlik/api/kimlik-api"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "products": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "Product[]",
        "resolved": "Product[]",
        "references": {
          "Product": {
            "location": "import",
            "path": "../../models/product"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    },
    "workspaceOwnerships": {
      "type": "unknown",
      "mutable": false,
      "complexType": {
        "original": "WorkspaceOwnership[]",
        "resolved": "WorkspaceOwnership[]",
        "references": {
          "WorkspaceOwnership": {
            "location": "import",
            "path": "../../models/workspace-ownership"
          }
        }
      },
      "required": false,
      "optional": false,
      "docs": {
        "tags": [],
        "text": ""
      }
    }
  }; }
  static get states() { return {
    "product": {},
    "error": {},
    "updateError": {},
    "deleteError": {},
    "showEditProductForm": {},
    "showDeleteConfirmation": {}
  }; }
}
