'use strict';

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

const index = require('./index-1141a245.js');
const listFetchState = require('./list-fetch-state-6f8f3bf8.js');
const itemFetchState = require('./item-fetch-state-4ed58ba8.js');
const damgaApi = require('./damga-api-1dea4125.js');
require('./data-model-01c368bc.js');
require('./apiBase-6c66ff1b.js');
require('./data-transfer-field-e8417d5f.js');
require('./BaseField-381327a9.js');
require('./filter-d5040f65.js');

const damgaDashboardCss = "damga-dashboard .graph-container{margin:calc(4 * var(--spacing-unit)) 0px calc(8 * var(--spacing-unit)) 0px}damga-dashboard .graph-container .graph-title{font-size:0.8em;margin-bottom:calc(2 * var(--spacing-unit));color:var(--color-text-secondary)}";

const DamgaDashboard = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.domains = listFetchState.ListFetchState.init();
    this.analyses = itemFetchState.ItemFetchState.init();
    this.relativeTime = 24 * 60;
    this.graphDateFormat = 'DD MMM, HH:mm';
    this.timeInterval = 30;
    this.startDate = undefined;
    this.endDate = undefined;
    this.selectedDomains = [];
  }
  componentWillLoad() {
    this.endDate = new Date();
    this.startDate = new Date(new Date().getTime() - (this.relativeTime * 60 * 1000));
    this.fetchList();
  }
  async fetchList() {
    var _a, _b;
    const { domains } = this;
    this.domains = this.domains.beforeFetch();
    const response = await this.apiDamga.getDomains().catch(error => {
      this.domains = domains.afterFetchError(error);
    });
    if (!response)
      return;
    this.domains = domains.afterFetch(response, false);
    this.domains.data.sort((a, b) => a.domain.localeCompare(b.domain));
    this.selectedDomains = [(_b = (_a = this.domains.data) === null || _a === void 0 ? void 0 : _a.at(0)) === null || _b === void 0 ? void 0 : _b.domain];
    this.fetchAnalyses();
  }
  async fetchAnalyses() {
    const { analyses, endDate, startDate, timeInterval } = this;
    this.analyses = this.analyses.beforeFetch();
    const response = await this.apiServicesDamga.getProxyAnalyses(this.selectedDomains, startDate, endDate, timeInterval).catch(error => {
      this.analyses = analyses.afterFetchError(error);
    });
    if (!response)
      return;
    this.analyses = analyses.afterFetch(response);
  }
  render() {
    var _a;
    const { analyses, graphDateFormat } = this;
    return (index.h(index.Host, { class: "container d-flex flex-grow-1 flex-column" }, index.h("div", null, index.h("div", { class: "d-flex align-items-center" }, index.h("dvn-select", { onChange: (e) => {
        // prevent redundant graph render
        this.analyses.isPending = true;
        this.relativeTime = Number(e.detail);
        if (this.relativeTime > 60 * 24 * 7) {
          // show month if viewing last month
          this.graphDateFormat = 'DD MMM, HH:mm';
          this.timeInterval = 180;
        }
        else if (this.relativeTime >= 60 * 24 * 7) {
          // show month if viewing last week
          this.graphDateFormat = 'DD MMM, HH:mm';
          this.timeInterval = 120;
        }
        else if (this.relativeTime >= 60 * 24) {
          // show day if viewing last 24 hours
          this.graphDateFormat = 'DD MMM, HH:mm';
          this.timeInterval = 30;
        }
        else if (this.relativeTime >= 60 * 3) {
          // show hour only if viewing last 3 to 12 hours
          this.graphDateFormat = 'HH:mm';
          this.timeInterval = 10;
        }
        else {
          // show hour only if viewing last 3 hours or less
          this.graphDateFormat = 'HH:mm';
          this.timeInterval = 5;
        }
        this.startDate = new Date(new Date().getTime() - (this.relativeTime * 60 * 1000));
        this.fetchAnalyses();
      }, value: `${this.relativeTime}`, disabled: this.analyses.isPending }, index.h("dvn-select-option", { value: `${30}` }, "Last 30 mins"), index.h("dvn-select-option", { value: `${60}` }, "Last hour"), index.h("dvn-select-option", { value: `${60 * 3}` }, "Last 3 hours"), index.h("dvn-select-option", { value: `${60 * 6}` }, "Last 6 hours"), index.h("dvn-select-option", { value: `${60 * 12}` }, "Last 12 hours"), index.h("dvn-select-option", { value: `${60 * 24}` }, "Last 24 hours"), index.h("dvn-select-option", { value: `${60 * 24 * 3}` }, "Last three days"), index.h("dvn-select-option", { value: `${60 * 24 * 5}` }, "Last five days"), index.h("dvn-select-option", { value: `${60 * 24 * 7}` }, "Last week"), index.h("dvn-select-option", { value: `${60 * 24 * 30}` }, "Last month")), index.h("dvn-select", { onChange: (e) => {
        // prevent redundant graph render
        this.analyses.isPending = true;
        this.timeInterval = Number(e.detail);
        this.fetchAnalyses();
      }, value: `${this.timeInterval}`, disabled: this.analyses.isPending }, index.h("dvn-select-option", { value: '5' }, "5 minutes"), index.h("dvn-select-option", { value: '10' }, "10 minutes"), index.h("dvn-select-option", { value: '30' }, "30 minutes"), index.h("dvn-select-option", { value: '60' }, "1 hour"), index.h("dvn-select-option", { value: '120' }, "2 hours"), index.h("dvn-select-option", { value: '180' }, "3 hours"), index.h("dvn-select-option", { value: '360' }, "6 hours"), index.h("dvn-select-option", { value: '720' }, "12 hours"), index.h("dvn-select-option", { value: '1440' }, "24 hours")), index.h("damga-proxy-graph-domain-filter", { value: this.selectedDomains, domains: ((_a = this.domains.data) === null || _a === void 0 ? void 0 : _a.map(({ domain }) => domain)) || [], onChange: (e) => {
        this.selectedDomains = e.detail;
        this.fetchAnalyses();
      }, isPending: analyses.isPending }), index.h("dvn-icon-button", { view: "flat", "icon-name": "uil uil-sync", onClick: () => this.fetchAnalyses(), progressing: this.analyses.isPending }))), analyses.data &&
      index.h(index.Fragment, null, index.h("div", { class: "graph-container" }, index.h("div", { class: "graph-title" }, "REQUESTS"), index.h("damga-proxy-graph", { valueKey: 'requests', data: analyses.data, isPending: analyses.isPending, dateFormat: graphDateFormat })), index.h("div", { class: "graph-container" }, index.h("div", { class: "graph-title" }, "AVERAGE TIME"), index.h("damga-proxy-graph", { valueKey: 'averageTime', data: analyses.data, isPending: analyses.isPending, dateFormat: graphDateFormat })), index.h("div", { class: "graph-container" }, index.h("div", { class: "graph-title" }, "BANDWIDTH (bytes)"), index.h("damga-proxy-graph", { valueKey: 'bandwidth', graphViewType: 'bar', data: analyses.data, isPending: analyses.isPending, dateFormat: graphDateFormat, graphOptions: { x: { stacked: true }, y: { stacked: true } } })), index.h("div", { class: "graph-container" }, index.h("div", { class: "graph-title" }, "Unique IPs"), index.h("damga-proxy-graph", { valueKey: 'uniqueIPCount', graphViewType: 'bar', data: analyses.data, isPending: analyses.isPending, dateFormat: graphDateFormat, graphOptions: { x: { stacked: true }, y: { stacked: true } } })), this.selectedDomains.length === 1 &&
        index.h(index.Fragment, null, index.h("div", { class: "graph-container" }, index.h("div", { class: "graph-title" }, "STATUSES"), index.h("damga-proxy-graph", { valueType: 'object', valueKey: 'requestsByStatus', graphViewType: 'bar', data: analyses.data, isPending: analyses.isPending, dateFormat: graphDateFormat, domains: this.selectedDomains, graphOptions: { x: { stacked: true }, y: { stacked: true } } })), index.h("div", { class: "graph-container" }, index.h("div", { class: "graph-title" }, "METHODS"), index.h("damga-proxy-graph", { valueType: 'object', valueKey: 'requestsByMethod', graphViewType: 'bar', data: analyses.data, isPending: analyses.isPending, dateFormat: graphDateFormat, domains: this.selectedDomains, graphOptions: { x: { stacked: true }, y: { stacked: true } } })), index.h("div", { class: "graph-container" }, index.h("div", { class: "graph-title" }, "COUNTRIES"), index.h("damga-proxy-graph", { valueType: 'object', valueKey: 'requestsByCountry', graphViewType: 'bar', data: analyses.data, isPending: analyses.isPending, dateFormat: graphDateFormat, domains: this.selectedDomains, graphOptions: { x: { stacked: true }, y: { stacked: true } } }))))));
  }
};
DamgaDashboard.style = damgaDashboardCss;

const DamgaHome = class {
  constructor(hostRef) {
    index.registerInstance(this, hostRef);
    this.selectedTab = 'domains';
    this.showDeleteConfirmation = false;
    this.showItemForm = false;
    this.listKey = 1;
    this.onClickAddNewItem = () => this.showItemForm = true;
    this.onConfirmDeleteItem = () => {
      let promise;
      if (this.selectedTab === 'load-balancers') {
        promise = this.apiDamga.deleteLoadBalancer(this.selectedItem._id);
      }
      else if (this.selectedTab === 'target-groups') {
        promise = this.apiDamga.deleteTargetGroup(this.selectedItem._id);
      }
      else if (this.selectedTab === 'domains') {
        promise = this.apiDamga.deleteDomain(this.selectedItem._id);
      }
      this.isDeletePending = true;
      promise === null || promise === void 0 ? void 0 : promise.then(this.invalidate).catch(this.onDeleteFail).finally(() => this.isDeletePending = false);
    };
    this.onDeleteFail = (error) => {
      var _a, _b, _c, _d;
      if (((_a = error.data) === null || _a === void 0 ? void 0 : _a.error) === 'target-group-used-in-load-balancers') {
        this.deleteErrorMessage = `Target group is being used by load balancers ${(_b = error.data.loadBalancers) === null || _b === void 0 ? void 0 : _b.map(lb => lb.name).join(', ')}.`;
      }
      else if (((_c = error.data) === null || _c === void 0 ? void 0 : _c.error) === 'load-balancer-used-in-domains') {
        this.deleteErrorMessage = `Load balancer is being used by domains ${(_d = error.data.domains) === null || _d === void 0 ? void 0 : _d.map(d => d.domain).join(', ')}.`;
      }
    };
    this.dismissItemFormDialog = () => {
      this.showItemForm = false;
      this.selectedItem = undefined;
    };
    this.dismissDeleteConfirmationDialog = () => {
      this.showDeleteConfirmation = false;
      this.selectedItem = undefined;
      this.deleteErrorMessage = undefined;
    };
    this.invalidate = () => {
      this.listKey += 1;
      this.showItemForm = false;
      this.showDeleteConfirmation = false;
      this.selectedItem = undefined;
      this.deleteErrorMessage = undefined;
    };
  }
  componentWillLoad() {
    var _a;
    this.apiDamga = new damgaApi.DamgaApi(this.apiEndpoint, this.apiHeaders, this.apiQueryParams);
    if (((_a = this.extraTabs) === null || _a === void 0 ? void 0 : _a.length) > 0) {
      this.selectedTab = this.extraTabs[0].key;
    }
  }
  onAction(event) {
    event.stopImmediatePropagation();
    const action = event.detail;
    switch (action.name) {
      case 'delete': {
        this.showDeleteConfirmation = true;
        this.selectedItem = action.params.item;
        break;
      }
      case 'edit': {
        this.showItemForm = true;
        this.selectedItem = action.params.item;
        break;
      }
    }
  }
  render() {
    const { apiDamga, extraTabs, selectedTab } = this;
    const tabs = [
      ...(extraTabs || []).map(tab => ({ label: tab.label, value: tab.key })),
      { label: 'Domains', value: 'domains' },
      { label: 'Load Balancers', value: 'load-balancers' },
      { label: 'Target Groups', value: 'target-groups' },
    ];
    const newItemLabels = {
      'domains': 'Domain',
      'load-balancers': 'Load Balancer',
      'target-groups': 'Target Group',
    };
    const customTab = extraTabs.find(tab => selectedTab === tab.key);
    return (index.h(index.Host, { class: "d-flex flex-column", style: { minHeight: 'calc(100vh - 50px)' } }, index.h("div", { class: "container" }, index.h("div", { class: "row" }, index.h("div", { class: "col-sm-12" }, index.h("div", { class: "d-flex align-items-center" }, index.h("div", { class: "flex-grow-1" }, index.h("dvn-menu", { orientation: "horizontal" }, tabs.map(({ label, value }) => (index.h("dvn-menu-item", { highlighted: value === selectedTab, onClick: () => this.selectedTab = value }, label))))), newItemLabels[selectedTab] &&
      index.h("dvn-button", { onClick: this.onClickAddNewItem }, "New ", newItemLabels[selectedTab]))))), customTab && customTab.render(), selectedTab === 'domains' &&
      index.h(index.Fragment, null, index.h("damga-domain-list", { key: this.listKey, apiDamga: apiDamga }), this.showItemForm &&
        index.h("dvn-dialog", { shown: true, onDismiss: this.dismissItemFormDialog }, index.h("damga-domain-form", { apiDamga: apiDamga, onChange: this.invalidate, item: this.selectedItem }))), selectedTab === 'load-balancers' &&
      index.h(index.Fragment, null, index.h("damga-load-balancer-list", { key: this.listKey, apiDamga: apiDamga }), this.showItemForm &&
        index.h("dvn-dialog", { shown: true, onDismiss: this.dismissItemFormDialog }, index.h("damga-load-balancer-form", { apiDamga: apiDamga, onChange: this.invalidate, item: this.selectedItem }))), selectedTab === 'target-groups' &&
      index.h(index.Fragment, null, index.h("damga-target-group-list", { key: this.listKey, apiDamga: apiDamga }), this.showItemForm &&
        index.h("dvn-dialog", { shown: true, onDismiss: this.dismissItemFormDialog }, index.h("damga-target-group-form", { apiDamga: apiDamga, onChange: this.invalidate, item: this.selectedItem }))), this.showDeleteConfirmation &&
      index.h("dvn-dialog", { shown: true, onDismiss: this.dismissDeleteConfirmationDialog, title: "Deletion" }, index.h("p", null, "Are you sure to delete this item? This action cannot be undone."), this.deleteErrorMessage &&
        index.h("p", { class: "text-danger" }, this.deleteErrorMessage), index.h("div", { slot: "actions" }, index.h("dvn-button", { view: "flat", onClick: this.dismissDeleteConfirmationDialog }, "Cancel"), index.h("dvn-button", { tint: "danger", disabled: this.isDeletePending, progressing: this.isDeletePending, onClick: this.onConfirmDeleteItem }, "Yes, Delete")))));
  }
};

exports.damga_dashboard = DamgaDashboard;
exports.damga_home = DamgaHome;
