'use strict';

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var isNil = require('../../node_modules/lodash-es/isNil.js');
require('core-js/modules/es.array.concat.js');
require('core-js/modules/es.object.values.js');
var React = require('react');
var PropTypes = require('prop-types');
var classnames = require('classnames');
var colors = require('@carbon/colors');
var react = require('@carbon/react');
var LayoutConstants = require('../../constants/LayoutConstants.js');
var CardIcon = require('../ImageCard/CardIcon.js');
var useMatchingThreshold = require('../../hooks/useMatchingThreshold.js');
var index = require('../Tooltip/index.js');
var cardUtilityFunctions = require('../../utils/cardUtilityFunctions.js');
var ValueRenderer = require('./ValueRenderer.js');
var UnitRenderer = require('./UnitRenderer.js');
var valueCardUtils = require('./valueCardUtils.js');
var iconsReact = require('@carbon/icons-react');

function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }

var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var React__default = /*#__PURE__*/_interopDefault(React);
var PropTypes__default = /*#__PURE__*/_interopDefault(PropTypes);
var classnames__default = /*#__PURE__*/_interopDefault(classnames);

var propTypes = {
  attribute: PropTypes__default.default.shape({
    label: PropTypes__default.default.string,
    unit: PropTypes__default.default.string,
    dataSourceId: PropTypes__default.default.string,
    measurementUnitLabel: PropTypes__default.default.string,
    // decimal precision
    precision: PropTypes__default.default.number,
    thresholds: PropTypes__default.default.arrayOf(PropTypes__default.default.shape({
      comparison: PropTypes__default.default.oneOf(['<', '>', '=', '<=', '>=']).isRequired,
      value: PropTypes__default.default.oneOfType([PropTypes__default.default.string, PropTypes__default.default.number]).isRequired,
      color: PropTypes__default.default.string,
      icon: PropTypes__default.default.string
    })),
    tooltip: PropTypes__default.default.string,
    // Position of threshold icon: 'label' (inline with label) or 'unit' (above unit)
    thresholdsIconPosition: PropTypes__default.default.oneOf(['label', 'unit'])
  }).isRequired,
  customFormatter: PropTypes__default.default.func,
  formatter: PropTypes__default.default.func,
  isEditable: PropTypes__default.default.bool,
  layout: PropTypes__default.default.oneOf(Object.values(LayoutConstants.CARD_LAYOUTS)),
  locale: PropTypes__default.default.string,
  /** whether to use translated labels in cards */
  shouldUseTranslatedLabels: PropTypes__default.default.bool,
  i18n: PropTypes__default.default.objectOf(PropTypes__default.default.any),
  renderIconByName: PropTypes__default.default.func,
  /** Optional trend information */
  secondaryValue: PropTypes__default.default.shape({
    color: PropTypes__default.default.string,
    trend: PropTypes__default.default.oneOf(['up', 'down']),
    value: PropTypes__default.default.oneOfType([PropTypes__default.default.string, PropTypes__default.default.bool, PropTypes__default.default.number]),
    href: PropTypes__default.default.string,
    onClick: PropTypes__default.default.func
  }),
  value: PropTypes__default.default.oneOfType([PropTypes__default.default.string, PropTypes__default.default.bool, PropTypes__default.default.number]),
  fontSize: PropTypes__default.default.number.isRequired,
  /** optional option to determine whether the number should be abbreviated (i.e. 10,000 = 10K) */
  isNumberValueCompact: PropTypes__default.default.bool.isRequired,
  /** number of attributes */
  attributeCount: PropTypes__default.default.number.isRequired,
  testId: PropTypes__default.default.string,
  /** callback when the attribute is clicked to trigger further action like opening a modal */
  onValueClick: PropTypes__default.default.func
};
var defaultProps = {
  layout: null,
  value: null,
  renderIconByName: null,
  secondaryValue: null,
  locale: 'en',
  customFormatter: null,
  formatter: null,
  isEditable: false,
  shouldUseTranslatedLabels: false,
  i18n: {},
  testId: 'attribute',
  onValueClick: null
};
var BEM_BASE = "".concat(valueCardUtils.BASE_CLASS_NAME, "__attribute");

/**
 * An attribute has a Value, Units and maybe a Threshold or Trend.
 * He also determines which threshold applies to a given attribute (perhaps that should be moved)
 */
var Attribute = function Attribute(_ref) {
  var _ref$attribute = _ref.attribute,
    label = _ref$attribute.label,
    unit = _ref$attribute.unit,
    thresholds = _ref$attribute.thresholds,
    precision = _ref$attribute.precision,
    dataSourceId = _ref$attribute.dataSourceId,
    measurementUnitLabel = _ref$attribute.measurementUnitLabel,
    tooltip = _ref$attribute.tooltip,
    _ref$attribute$thresh = _ref$attribute.thresholdsIconPosition,
    thresholdsIconPosition = _ref$attribute$thresh === void 0 ? 'unit' : _ref$attribute$thresh,
    attributeCount = _ref.attributeCount,
    customFormatter = _ref.customFormatter,
    formatter = _ref.formatter,
    isEditable = _ref.isEditable,
    layout = _ref.layout,
    locale = _ref.locale,
    shouldUseTranslatedLabels = _ref.shouldUseTranslatedLabels,
    i18n = _ref.i18n,
    renderIconByName = _ref.renderIconByName,
    secondaryValue = _ref.secondaryValue,
    value = _ref.value,
    fontSize = _ref.fontSize,
    isNumberValueCompact = _ref.isNumberValueCompact,
    testId = _ref.testId,
    onValueClick = _ref.onValueClick;
  var matchedThreshold = useMatchingThreshold({
    thresholds: thresholds,
    value: value
  });

  // matching threshold will be the first match in the list, or a value of null if not isEditable
  var matchingThreshold = thresholds ? isEditable ? thresholds[0] : matchedThreshold : null;
  var valueColor = matchingThreshold && matchingThreshold.icon === undefined ? matchingThreshold.color : null;

  // need to reduce the width size to fit multiple attributes when card layout is horizontal
  var attributeWidthPercentage = layout === LayoutConstants.CARD_LAYOUTS.HORIZONTAL ? 100 / attributeCount : 100;

  // Get translated label if shouldUseTranslatedLabels is true
  var displayLabel = cardUtilityFunctions.getTranslatedLabel(label, shouldUseTranslatedLabels, i18n);
  var displayUnitLabel = cardUtilityFunctions.getTranslatedLabel(unit, shouldUseTranslatedLabels, i18n);

  // Render threshold icon component
  var renderThresholdIcon = function renderThresholdIcon() {
    if (!(matchingThreshold !== null && matchingThreshold !== void 0 && matchingThreshold.icon)) return null;
    return /*#__PURE__*/React__default.default.createElement(CardIcon, {
      fill: matchingThreshold.color,
      color: matchingThreshold.color,
      width: 16,
      height: 16,
      title: "".concat(matchingThreshold.comparison, " ").concat(matchingThreshold.value),
      renderIconByName: renderIconByName,
      icon: matchingThreshold.icon,
      testId: "".concat(testId, "-threshold-icon"),
      className: classnames__default.default(_defineProperty__default.default(_defineProperty__default.default({}, "".concat(BEM_BASE, "-threshold-icon"), thresholdsIconPosition === 'unit'), "".concat(BEM_BASE, "-label-icon"), thresholdsIconPosition === 'label'))
    });
  };
  return /*#__PURE__*/React__default.default.createElement("div", {
    className: classnames__default.default("".concat(BEM_BASE, "-wrapper"), _defineProperty__default.default(_defineProperty__default.default({}, "".concat(BEM_BASE, "-wrapper--vertical"), layout === LayoutConstants.CARD_LAYOUTS.VERTICAL), "".concat(BEM_BASE, "-wrapper--horizontal"), layout === LayoutConstants.CARD_LAYOUTS.HORIZONTAL)),
    style: {
      '--value-card-attribute-width': "".concat(attributeWidthPercentage, "%")
    }
  }, /*#__PURE__*/React__default.default.createElement("div", {
    className: classnames__default.default("".concat(BEM_BASE, "-label"), _defineProperty__default.default({}, "".concat(BEM_BASE, "-label--with-icon"), thresholdsIconPosition === 'label' && (matchingThreshold === null || matchingThreshold === void 0 ? void 0 : matchingThreshold.icon)))
  }, thresholdsIconPosition === 'label' && renderThresholdIcon(), tooltip ? /*#__PURE__*/React__default.default.createElement(index.Tooltip, {
    direction: "right",
    showIcon: false,
    triggerText: displayLabel
  }, /*#__PURE__*/React__default.default.createElement("p", null, tooltip)) : /*#__PURE__*/React__default.default.createElement("span", {
    "data-testid": "".concat(testId, "-threshold-label")
  }, displayLabel)), /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(BEM_BASE)
  }, /*#__PURE__*/React__default.default.createElement(ValueRenderer, {
    value: value,
    layout: layout,
    precision: precision,
    color: valueColor,
    locale: locale
    // Prefer new formatter. Fall back to legacy customFormatter.
    ,
    formatter: formatter,
    customFormatter: customFormatter,
    fontSize: fontSize,
    isNumberValueCompact: isNumberValueCompact,
    testId: "".concat(testId, "-value"),
    dataSourceId: dataSourceId,
    onClick: onValueClick
  }), /*#__PURE__*/React__default.default.createElement("div", {
    className: "".concat(BEM_BASE, "-unit-with-icon")
  }, thresholdsIconPosition === 'unit' && renderThresholdIcon(), /*#__PURE__*/React__default.default.createElement(UnitRenderer, {
    unit: measurementUnitLabel || displayUnitLabel,
    testId: "".concat(testId, "-unit")
  }))), !isNil(secondaryValue) ? /*#__PURE__*/React__default.default.createElement("div", {
    "data-testid": "".concat(testId, "-secondary-value"),
    className: "".concat(BEM_BASE, "-secondary-value"),
    style: {
      '--secondary-value-color': colors.gray60
    }
  }, secondaryValue.trend === 'up' ? /*#__PURE__*/React__default.default.createElement(iconsReact.CaretUp, {
    className: "".concat(BEM_BASE, "_trend-icon"),
    "aria-label": "trending up",
    "data-testid": "".concat(testId, "-trending-up"),
    fill: secondaryValue.color || colors.gray60
  }) : secondaryValue.trend === 'down' ? /*#__PURE__*/React__default.default.createElement(iconsReact.CaretDown, {
    className: "".concat(BEM_BASE, "_trend-icon"),
    "aria-label": "trending down",
    "data-testid": "".concat(testId, "-trending-down"),
    fill: secondaryValue.color || colors.gray60
  }) : null, secondaryValue.href || secondaryValue.onClick ? /*#__PURE__*/React__default.default.createElement(react.Link, {
    "data-testid": "".concat(testId, "-secondary-value--link"),
    className: "".concat(BEM_BASE, "-secondary-value--link"),
    href: secondaryValue === null || secondaryValue === void 0 ? void 0 : secondaryValue.href,
    rel: "noopener noreferrer",
    onClick: function onClick() {
      return secondaryValue === null || secondaryValue === void 0 ? void 0 : secondaryValue.onClick({
        dataSourceId: dataSourceId,
        secondaryValue: secondaryValue
      });
    }
  }, secondaryValue.value) : secondaryValue.value) : null);
};
Attribute.propTypes = propTypes;
Attribute.defaultProps = defaultProps;
Attribute.__docgenInfo = {
  "description": "An attribute has a Value, Units and maybe a Threshold or Trend.\nHe also determines which threshold applies to a given attribute (perhaps that should be moved)",
  "methods": [],
  "displayName": "Attribute",
  "props": {
    "layout": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "enum",
        "computed": true,
        "value": "Object.values(CARD_LAYOUTS)"
      },
      "required": false
    },
    "value": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "union",
        "value": [{
          "name": "string"
        }, {
          "name": "bool"
        }, {
          "name": "number"
        }]
      },
      "required": false
    },
    "renderIconByName": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "secondaryValue": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "Optional trend information",
      "type": {
        "name": "shape",
        "value": {
          "color": {
            "name": "string",
            "required": false
          },
          "trend": {
            "name": "enum",
            "value": [{
              "value": "'up'",
              "computed": false
            }, {
              "value": "'down'",
              "computed": false
            }],
            "required": false
          },
          "value": {
            "name": "union",
            "value": [{
              "name": "string"
            }, {
              "name": "bool"
            }, {
              "name": "number"
            }],
            "required": false
          },
          "href": {
            "name": "string",
            "required": false
          },
          "onClick": {
            "name": "func",
            "required": false
          }
        }
      },
      "required": false
    },
    "locale": {
      "defaultValue": {
        "value": "'en'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "customFormatter": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "formatter": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "isEditable": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "shouldUseTranslatedLabels": {
      "defaultValue": {
        "value": "false",
        "computed": false
      },
      "description": "whether to use translated labels in cards",
      "type": {
        "name": "bool"
      },
      "required": false
    },
    "i18n": {
      "defaultValue": {
        "value": "{}",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "objectOf",
        "value": {
          "name": "any"
        }
      },
      "required": false
    },
    "testId": {
      "defaultValue": {
        "value": "'attribute'",
        "computed": false
      },
      "description": "",
      "type": {
        "name": "string"
      },
      "required": false
    },
    "onValueClick": {
      "defaultValue": {
        "value": "null",
        "computed": false
      },
      "description": "callback when the attribute is clicked to trigger further action like opening a modal",
      "type": {
        "name": "func"
      },
      "required": false
    },
    "attribute": {
      "description": "",
      "type": {
        "name": "shape",
        "value": {
          "label": {
            "name": "string",
            "required": false
          },
          "unit": {
            "name": "string",
            "required": false
          },
          "dataSourceId": {
            "name": "string",
            "required": false
          },
          "measurementUnitLabel": {
            "name": "string",
            "required": false
          },
          "precision": {
            "name": "number",
            "required": false
          },
          "thresholds": {
            "name": "arrayOf",
            "value": {
              "name": "shape",
              "value": {
                "comparison": {
                  "name": "enum",
                  "value": [{
                    "value": "'<'",
                    "computed": false
                  }, {
                    "value": "'>'",
                    "computed": false
                  }, {
                    "value": "'='",
                    "computed": false
                  }, {
                    "value": "'<='",
                    "computed": false
                  }, {
                    "value": "'>='",
                    "computed": false
                  }],
                  "required": true
                },
                "value": {
                  "name": "union",
                  "value": [{
                    "name": "string"
                  }, {
                    "name": "number"
                  }],
                  "required": true
                },
                "color": {
                  "name": "string",
                  "required": false
                },
                "icon": {
                  "name": "string",
                  "required": false
                }
              }
            },
            "required": false
          },
          "tooltip": {
            "name": "string",
            "required": false
          },
          "thresholdsIconPosition": {
            "name": "enum",
            "value": [{
              "value": "'label'",
              "computed": false
            }, {
              "value": "'unit'",
              "computed": false
            }],
            "required": false
          }
        }
      },
      "required": true
    },
    "fontSize": {
      "description": "",
      "type": {
        "name": "number"
      },
      "required": true
    },
    "isNumberValueCompact": {
      "description": "optional option to determine whether the number should be abbreviated (i.e. 10,000 = 10K)",
      "type": {
        "name": "bool"
      },
      "required": true
    },
    "attributeCount": {
      "description": "number of attributes",
      "type": {
        "name": "number"
      },
      "required": true
    }
  }
};
var Attribute$1 = Attribute;

module.exports = Attribute$1;
