import { jsxs, jsx } from 'react/jsx-runtime';
import { PureComponent } from 'react';
import { css } from '@emotion/css';
import { uniqueId } from 'lodash';
import '@grafana/data';
import { stylesFactory, Button, LegacyForms, Icon } from '@grafana/ui';

var __defProp = Object.defineProperty;
var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
var __publicField = (obj, key, value) => __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
const getCustomHeaderRowStyles = stylesFactory(() => {
  return {
    layout: css`
      display: flex;
      align-items: center;
      margin-bottom: 4px;
      > * {
        margin-left: 4px;
        margin-bottom: 0;
        height: 100%;
        &:first-child,
        &:last-child {
          margin-left: 0;
        }
      }
    `
  };
});
const CustomHeaderRow = ({ header, onBlur, onChange, onRemove, onReset }) => {
  const styles = getCustomHeaderRowStyles();
  return /* @__PURE__ */ jsxs("div", { className: styles.layout, children: [
    /* @__PURE__ */ jsx(
      LegacyForms.FormField,
      {
        label: "Header",
        name: "name",
        placeholder: "X-Custom-Header",
        labelWidth: 5,
        value: header.name || "",
        onChange: (e) => onChange({ ...header, name: e.target.value }),
        onBlur
      }
    ),
    /* @__PURE__ */ jsx(
      LegacyForms.SecretFormField,
      {
        label: "Value",
        "aria-label": "Value",
        name: "value",
        isConfigured: header.configured,
        value: header.value,
        labelWidth: 5,
        inputWidth: header.configured ? 11 : 12,
        placeholder: "Header Value",
        onReset: () => onReset(header.id),
        onChange: (e) => onChange({ ...header, value: e.target.value }),
        onBlur
      }
    ),
    /* @__PURE__ */ jsx(
      Button,
      {
        type: "button",
        "aria-label": "Remove header",
        variant: "secondary",
        size: "xs",
        onClick: (_e) => onRemove(header.id),
        children: /* @__PURE__ */ jsx(Icon, { name: "trash-alt" })
      }
    )
  ] });
};
CustomHeaderRow.displayName = "CustomHeaderRow";
class CustomHeadersSettings extends PureComponent {
  constructor(props) {
    super(props);
    __publicField(this, "state", {
      headers: []
    });
    __publicField(this, "updateSettings", () => {
      const { headers } = this.state;
      const newJsonData = Object.fromEntries(
        Object.entries(this.props.dataSourceConfig.jsonData).filter(([key, val]) => !key.startsWith("httpHeaderName"))
      );
      const newSecureJsonData = Object.fromEntries(
        Object.entries(this.props.dataSourceConfig.secureJsonData || {}).filter(
          ([key, val]) => !key.startsWith("httpHeaderValue")
        )
      );
      for (const [index, header] of headers.entries()) {
        newJsonData[`httpHeaderName${index + 1}`] = header.name;
        if (!header.configured) {
          newSecureJsonData[`httpHeaderValue${index + 1}`] = header.value;
        }
      }
      this.props.onChange({
        ...this.props.dataSourceConfig,
        jsonData: newJsonData,
        secureJsonData: newSecureJsonData
      });
    });
    __publicField(this, "onHeaderAdd", () => {
      this.setState((prevState) => {
        return {
          headers: [...prevState.headers, { id: uniqueId(), name: "", value: "", configured: false }]
        };
      });
    });
    __publicField(this, "onHeaderChange", (headerIndex, value) => {
      this.setState(({ headers }) => {
        return {
          headers: headers.map((item, index) => {
            if (headerIndex !== index) {
              return item;
            }
            return { ...value };
          })
        };
      });
    });
    __publicField(this, "onHeaderReset", (headerId) => {
      this.setState(({ headers }) => {
        return {
          headers: headers.map((h, i) => {
            if (h.id !== headerId) {
              return h;
            }
            return {
              ...h,
              value: "",
              configured: false
            };
          })
        };
      });
    });
    __publicField(this, "onHeaderRemove", (headerId) => {
      this.setState(
        ({ headers }) => ({
          headers: headers.filter((h) => h.id !== headerId)
        }),
        this.updateSettings
      );
    });
    const { jsonData, secureJsonData, secureJsonFields } = this.props.dataSourceConfig;
    this.state = {
      headers: Object.keys(jsonData).sort().filter((key) => key.startsWith("httpHeaderName")).map((key, index) => {
        return {
          id: uniqueId(),
          name: jsonData[key],
          value: secureJsonData !== undefined ? secureJsonData[key] : "",
          configured: secureJsonFields && secureJsonFields[`httpHeaderValue${index + 1}`] || false
        };
      })
    };
  }
  render() {
    const { headers } = this.state;
    return /* @__PURE__ */ jsxs("div", { className: "gf-form-group", children: [
      /* @__PURE__ */ jsx("div", { className: "gf-form", children: /* @__PURE__ */ jsx("h6", { children: "Custom HTTP Headers" }) }),
      /* @__PURE__ */ jsx("div", { children: headers.map((header, i) => /* @__PURE__ */ jsx(
        CustomHeaderRow,
        {
          header,
          onChange: (h) => {
            this.onHeaderChange(i, h);
          },
          onBlur: this.updateSettings,
          onRemove: this.onHeaderRemove,
          onReset: this.onHeaderReset
        },
        header.id
      )) }),
      /* @__PURE__ */ jsx("div", { className: "gf-form", children: /* @__PURE__ */ jsx(
        Button,
        {
          variant: "secondary",
          icon: "plus",
          type: "button",
          onClick: (e) => {
            this.onHeaderAdd();
          },
          children: "Add header"
        }
      ) })
    ] });
  }
}

export { CustomHeadersSettings, CustomHeadersSettings as default };
//# sourceMappingURL=CustomHeadersSettings.js.map
