'use strict';

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var isNil = require('../../node_modules/lodash-es/isNil.js');
require('core-js/modules/es.symbol.js');
require('core-js/modules/es.array.filter.js');
require('core-js/modules/es.array.find.js');
require('core-js/modules/es.array.includes.js');
require('core-js/modules/es.array.map.js');
require('core-js/modules/es.number.is-integer.js');
require('core-js/modules/es.object.get-own-property-descriptor.js');
require('core-js/modules/es.object.get-own-property-descriptors.js');
require('core-js/modules/es.object.keys.js');
require('core-js/modules/es.object.to-string.js');
require('core-js/modules/es.regexp.exec.js');
require('core-js/modules/es.string.includes.js');
require('core-js/modules/es.string.replace.js');
require('core-js/modules/web.dom-collections.for-each.js');
var React = require('react');
var react = require('@carbon/react');
var cardUtilityFunctions = require('../../utils/cardUtilityFunctions.js');
var dayjs = require('../../utils/dayjs.js');

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

var _defineProperty__default = /*#__PURE__*/_interopDefault(_defineProperty);
var React__default = /*#__PURE__*/_interopDefault(React);

function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty__default.default(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var determinePrecisionAndValue = function determinePrecisionAndValue() {
  var precision = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
  var value = arguments.length > 1 ? arguments[1] : undefined;
  var locale = arguments.length > 2 ? arguments[2] : undefined;
  var precisionDefined = Number.isInteger(value) ? 0 : precision;
  if (typeof value === 'number') {
    return cardUtilityFunctions.formatNumberWithPrecision(value, precisionDefined, locale, false);
  }
  if (isNil(value)) {
    return '--';
  }
  return '--';
};

/**
 * Updates the hrefs in each column to be us-able links. If href variables are on a table that has row specific values, the user
 * should not pass in a cardVariables object as each variable with have multiple values.
 * @param {Array<Object>} columns - Array of TableCard columns
 * @return {array} array of columns with formatted links and updated variable values
 */
var createColumnsWithFormattedLinks = function createColumnsWithFormattedLinks(columns) {
  var defaultDateFormatPattern = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : dayjs.DAYJS_INPUT_FORMATS.SECONDS;
  return columns.map(function (column) {
    var linkTemplate = column.linkTemplate;
    if (linkTemplate) {
      // get the variable names from the href
      var variables = linkTemplate.href ? cardUtilityFunctions.getVariables(linkTemplate.href) : [];
      return _objectSpread(_objectSpread({}, column), {}, {
        // eslint-disable-next-line react/prop-types
        renderDataFunction: function renderDataFunction(_ref) {
          var value = _ref.value,
            row = _ref.row;
          var variableLink;
          // if we have variables the value is based on its own row's context
          if (variables && variables.length) {
            variableLink = linkTemplate.href;
            variables.forEach(function (variable) {
              var matchingColumn = columns.find(function (variableColumn) {
                return variableColumn.dataSourceId === variable;
              });
              var variableValue =
              // format the TIMESTAMP type columns
              (matchingColumn === null || matchingColumn === void 0 ? void 0 : matchingColumn.type) === 'TIMESTAMP' ? dayjs.default.tz(row[variable]).format(defaultDateFormatPattern) : row[variable];
              // encode value so the URL can be valid
              var encodedValue = typeof variableValue === 'string' && variableValue !== null && variableValue !== void 0 && variableValue.includes('https') ? variableValue : encodeURIComponent(variableValue);
              variableLink = variableLink.replace("{".concat(variable, "}"), encodedValue);
            });
          }
          return /*#__PURE__*/React__default.default.createElement(react.Link, {
            href: variableLink || linkTemplate.href,
            target: linkTemplate.target ? linkTemplate.target : null
          }, value);
        }
      });
    }
    return column;
  });
};

/**
 * Updates expandedRow to have us-able links if any hrefs are found. If href variables are on a table that has
 * row specific values, the user should not pass in a cardVariables object as each variable with have multiple values.
 * @param {object} row - Object containing each value present on the row
 * @param {Array<Object>} expandedRow - Array of data to display when the row is expanded
 * @param {object} cardVariables - object of cardVariables
 * @return {array} Array of data with formatted links to display when the row is expanded
 */
var handleExpandedItemLinks = function handleExpandedItemLinks(row, expandedRow, cardVariables) {
  // if the user has given us variable values, we can assume that they don't want them to be row specific
  if (cardVariables) {
    return expandedRow;
  }
  var updatedExpandedRow = [];
  expandedRow.forEach(function (item) {
    var linkTemplate = item.linkTemplate;
    var variables = linkTemplate !== null && linkTemplate !== void 0 && linkTemplate.href ? cardUtilityFunctions.getVariables(linkTemplate.href) : [];
    var variableLink;
    // if we have variables the value is based on its own row's context
    if (variables && variables.length) {
      variableLink = linkTemplate.href;
      variables.forEach(function (variable) {
        var variableValue = row[variable];
        // encode value so the URL can be valid
        var encodedValue = encodeURIComponent(variableValue);
        variableLink = variableLink.replace("{".concat(variable, "}"), encodedValue);
      });
    }
    if (linkTemplate) {
      updatedExpandedRow.push(_objectSpread(_objectSpread({}, item), {}, {
        linkTemplate: _objectSpread(_objectSpread({}, linkTemplate), {}, {
          href: variableLink || linkTemplate.href
        })
      }));
    } else {
      updatedExpandedRow.push(item);
    }
  });
  return updatedExpandedRow;
};

/**
 *
 * @param {*} column
 * @param {*} defaultFilterStringPlaceholdText
 * @returns  what the filter object should be
 */
var determineFilterFunction = function determineFilterFunction(column, defaultFilterStringPlaceholdText) {
  var defaultDateFormatPattern = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : dayjs.DAYJS_INPUT_FORMATS.SECONDS;
  return _objectSpread(_objectSpread({}, column.type === 'TIMESTAMP' ? {
    filterFunction: function filterFunction(cellValue, filterValue) {
      var dateString = dayjs.default.tz(cellValue).format(defaultDateFormatPattern);
      return dateString.includes(filterValue);
    }
  } : {}), {}, {
    // only add custom filter for timestamps
    placeholderText: defaultFilterStringPlaceholdText
  }, column.filter ? column.filter : {});
};

exports.createColumnsWithFormattedLinks = createColumnsWithFormattedLinks;
exports.determineFilterFunction = determineFilterFunction;
exports.determinePrecisionAndValue = determinePrecisionAndValue;
exports.handleExpandedItemLinks = handleExpandedItemLinks;
