"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.AnalyticsCollectionCardWithLens = exports.AnalyticsCollectionCard = void 0;
var _react = _interopRequireDefault(require("react"));
var _history = require("history");
var _kea = require("kea");
var _charts = require("@elastic/charts");
var _eui = require("@elastic/eui");
var _i18n = require("@kbn/i18n");
var _uiTheme = require("@kbn/ui-theme");
var _encode_path_params = require("../../../../shared/encode_path_params");
var _kibana = require("../../../../shared/kibana");
var _with_lens_data = require("../../../hoc/with_lens_data");
var _routes = require("../../../routes");
var _get_formula_by_filter = require("../../../utils/get_formula_by_filter");
var _analytics_collection_card = require("./analytics_collection_card.styles");
/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License
 * 2.0; you may not use this file except in compliance with the Elastic License
 * 2.0.
 */
var ChartStatus;
(function (ChartStatus) {
  ChartStatus["INCREASE"] = "increase";
  ChartStatus["DECREASE"] = "decrease";
  ChartStatus["CONSTANT"] = "constant";
})(ChartStatus || (ChartStatus = {}));
const getCardTheme = euiTheme => ({
  [ChartStatus.DECREASE]: {
    area: _uiTheme.euiThemeVars.euiColorVis7_behindText,
    areaOpacity: 0.2,
    icon: 'sortDown',
    line: _uiTheme.euiThemeVars.euiColorVis7,
    lineOpacity: 0.5,
    text: '#996130'
  },
  [ChartStatus.CONSTANT]: {
    area: euiTheme.colors.mediumShade,
    areaOpacity: 0.2,
    icon: 'minus',
    line: euiTheme.colors.mediumShade,
    lineOpacity: 0.5,
    text: euiTheme.colors.darkShade
  },
  [ChartStatus.INCREASE]: {
    area: _uiTheme.euiThemeVars.euiColorVis0_behindText,
    areaOpacity: 0.2,
    icon: 'sortUp',
    line: _uiTheme.euiThemeVars.euiColorVis0,
    lineOpacity: 0.5,
    text: '#387765'
  }
});
const getChartStatus = metric => {
  if (metric && metric > 0) return ChartStatus.INCREASE;
  if (metric && metric < 0) return ChartStatus.DECREASE;
  return ChartStatus.CONSTANT;
};
const AnalyticsCollectionCard = ({
  collection,
  isLoading,
  isCreatedByEngine,
  subtitle,
  data,
  metric,
  secondaryMetric
}) => {
  const {
    euiTheme
  } = (0, _eui.useEuiTheme)();
  const {
    history,
    navigateToUrl
  } = (0, _kea.useValues)(_kibana.KibanaLogic);
  const cardStyles = (0, _analytics_collection_card.AnalyticsCollectionCardStyles)(euiTheme);
  const status = getChartStatus(secondaryMetric);
  const CARD_THEME = getCardTheme(euiTheme)[status];
  const collectionViewUrl = (0, _encode_path_params.generateEncodedPath)(_routes.COLLECTION_OVERVIEW_PATH, {
    name: collection.name
  });
  const handleCardClick = event => {
    event === null || event === void 0 ? void 0 : event.preventDefault();
    navigateToUrl(collectionViewUrl);
  };
  return /*#__PURE__*/_react.default.createElement(_eui.EuiCard, {
    titleSize: "s",
    titleElement: "h4",
    title: /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement("span", {
      css: cardStyles.title
    }, collection.name), isCreatedByEngine && /*#__PURE__*/_react.default.createElement(_eui.EuiBadge, {
      color: "hollow",
      iconType: "link",
      css: cardStyles.badge
    }, _i18n.i18n.translate('xpack.enterpriseSearch.analytics.collection.badge', {
      defaultMessage: 'Engine'
    }))),
    textAlign: "left",
    css: cardStyles.card,
    description: /*#__PURE__*/_react.default.createElement("span", {
      css: cardStyles.subtitle
    }, subtitle),
    href: history.createHref((0, _history.parsePath)(collectionViewUrl)),
    onClick: handleCardClick,
    footer: isLoading ? /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
      alignItems: "center",
      justifyContent: "center"
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiLoadingChart, {
      size: "m"
    })) : /*#__PURE__*/_react.default.createElement(_eui.EuiFlexGroup, {
      direction: "column",
      gutterSize: "s",
      alignItems: "flexEnd",
      justifyContent: "flexEnd",
      css: cardStyles.footer
    }, /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
      size: "s",
      color: CARD_THEME.text
    }, secondaryMetric === null ? _i18n.i18n.translate('xpack.enterpriseSearch.analytics.collection.notAvailableLabel', {
      defaultMessage: 'N/A'
    }) : /*#__PURE__*/_react.default.createElement(_react.default.Fragment, null, /*#__PURE__*/_react.default.createElement(_eui.EuiIcon, {
      type: CARD_THEME.icon
    }), secondaryMetric, "%")), /*#__PURE__*/_react.default.createElement(_eui.EuiText, {
      color: CARD_THEME.text
    }, /*#__PURE__*/_react.default.createElement("h2", null, metric === null ? _i18n.i18n.translate('xpack.enterpriseSearch.analytics.collection.notAvailableLabel', {
      defaultMessage: 'N/A'
    }) : /*#__PURE__*/_react.default.createElement(_eui.EuiI18nNumber, {
      value: metric
    }))))
  }, !isLoading && (data === null || data === void 0 ? void 0 : data.some(([, y]) => y && y !== 0)) && /*#__PURE__*/_react.default.createElement(_charts.Chart, {
    size: ['100%', 130],
    css: cardStyles.chart
  }, /*#__PURE__*/_react.default.createElement(_charts.Settings, {
    theme: {
      areaSeriesStyle: {
        area: {
          fill: CARD_THEME.area,
          opacity: CARD_THEME.areaOpacity
        },
        line: {
          opacity: CARD_THEME.lineOpacity,
          stroke: CARD_THEME.line,
          strokeWidth: 2
        }
      },
      chartMargins: {
        bottom: 0,
        left: 0,
        right: 0,
        top: 0
      }
    },
    showLegend: false
  }), /*#__PURE__*/_react.default.createElement(_charts.Tooltip, {
    type: "none"
  }), /*#__PURE__*/_react.default.createElement(_charts.AreaSeries, {
    id: collection.name,
    data: data,
    xAccessor: 0,
    yAccessors: [1],
    xScaleType: _charts.ScaleType.Time,
    yScaleType: _charts.ScaleType.Linear,
    curve: _charts.CurveType.CURVE_BASIS,
    yNice: true
  })));
};
exports.AnalyticsCollectionCard = AnalyticsCollectionCard;
const LENS_LAYERS = {
  metrics: {
    hitsTotal: 'hitsTotal',
    id: 'metrics',
    percentage: 'percentage'
  },
  trend: {
    id: 'trend',
    x: 'timeline',
    y: 'values'
  }
};
const initialValues = {
  data: [],
  isLoading: true,
  metric: null,
  secondaryMetric: null
};
const AnalyticsCollectionCardWithLens = (0, _with_lens_data.withLensData)(AnalyticsCollectionCard, {
  dataLoadTransform: (isLoading, adapters) => {
    var _adapters$tables, _adapters$tables$tabl, _adapters$tables$tabl2, _adapters$tables$tabl3, _adapters$tables2, _adapters$tables2$tab, _adapters$tables2$tab2, _adapters$tables2$tab3, _adapters$tables$tabl4, _adapters$tables3, _adapters$tables3$tab, _adapters$tables3$tab2, _adapters$tables3$tab3;
    return isLoading || !adapters ? initialValues : {
      data: ((_adapters$tables = adapters.tables) === null || _adapters$tables === void 0 ? void 0 : (_adapters$tables$tabl = _adapters$tables.tables[LENS_LAYERS.trend.id]) === null || _adapters$tables$tabl === void 0 ? void 0 : (_adapters$tables$tabl2 = _adapters$tables$tabl.rows) === null || _adapters$tables$tabl2 === void 0 ? void 0 : _adapters$tables$tabl2.map(row => [row[LENS_LAYERS.trend.x], row[LENS_LAYERS.trend.y]])) || [],
      isLoading: false,
      metric: (_adapters$tables$tabl3 = (_adapters$tables2 = adapters.tables) === null || _adapters$tables2 === void 0 ? void 0 : (_adapters$tables2$tab = _adapters$tables2.tables[LENS_LAYERS.metrics.id]) === null || _adapters$tables2$tab === void 0 ? void 0 : (_adapters$tables2$tab2 = _adapters$tables2$tab.rows) === null || _adapters$tables2$tab2 === void 0 ? void 0 : (_adapters$tables2$tab3 = _adapters$tables2$tab2[0]) === null || _adapters$tables2$tab3 === void 0 ? void 0 : _adapters$tables2$tab3[LENS_LAYERS.metrics.hitsTotal]) !== null && _adapters$tables$tabl3 !== void 0 ? _adapters$tables$tabl3 : null,
      secondaryMetric: (_adapters$tables$tabl4 = (_adapters$tables3 = adapters.tables) === null || _adapters$tables3 === void 0 ? void 0 : (_adapters$tables3$tab = _adapters$tables3.tables[LENS_LAYERS.metrics.id]) === null || _adapters$tables3$tab === void 0 ? void 0 : (_adapters$tables3$tab2 = _adapters$tables3$tab.rows) === null || _adapters$tables3$tab2 === void 0 ? void 0 : (_adapters$tables3$tab3 = _adapters$tables3$tab2[0]) === null || _adapters$tables3$tab3 === void 0 ? void 0 : _adapters$tables3$tab3[LENS_LAYERS.metrics.percentage]) !== null && _adapters$tables$tabl4 !== void 0 ? _adapters$tables$tabl4 : null
    };
  },
  getAttributes: (dataView, formulaApi, {
    filterBy
  }) => {
    let metric = formulaApi.insertOrReplaceFormulaColumn(LENS_LAYERS.metrics.percentage, {
      formula: `round(((${(0, _get_formula_by_filter.getFormulaByFilter)(filterBy)}/${(0, _get_formula_by_filter.getFormulaByFilter)(filterBy, 'previous')})-1) * 100)`,
      label: ' '
    }, {
      columnOrder: [],
      columns: {}
    }, dataView);
    metric = formulaApi.insertOrReplaceFormulaColumn(LENS_LAYERS.metrics.hitsTotal, {
      formula: (0, _get_formula_by_filter.getFormulaByFilter)(filterBy),
      label: ' '
    }, metric, dataView);
    return {
      references: [{
        id: dataView.id,
        name: 'indexpattern-datasource-current-indexpattern',
        type: 'index-pattern'
      }, {
        id: dataView.id,
        name: `indexpattern-datasource-layer-${LENS_LAYERS.trend.id}`,
        type: 'index-pattern'
      }, {
        id: dataView.id,
        name: `indexpattern-datasource-layer-${LENS_LAYERS.metrics.id}`,
        type: 'index-pattern'
      }],
      state: {
        datasourceStates: {
          formBased: {
            layers: {
              [LENS_LAYERS.trend.id]: formulaApi.insertOrReplaceFormulaColumn(LENS_LAYERS.trend.y, {
                formula: (0, _get_formula_by_filter.getFormulaByFilter)(filterBy)
              }, {
                columnOrder: [],
                columns: {
                  [LENS_LAYERS.trend.x]: {
                    dataType: 'date',
                    isBucketed: false,
                    label: 'Timestamp',
                    operationType: 'date_histogram',
                    params: {
                      includeEmptyRows: true,
                      interval: 'auto'
                    },
                    scale: 'ordinal',
                    sourceField: dataView === null || dataView === void 0 ? void 0 : dataView.timeFieldName
                  }
                }
              }, dataView),
              [LENS_LAYERS.metrics.id]: metric
            }
          }
        },
        filters: [],
        query: {
          language: 'kuery',
          query: ''
        },
        visualization: {
          layerId: [LENS_LAYERS.metrics.id],
          layerType: 'data',
          metricAccessor: LENS_LAYERS.metrics.hitsTotal,
          secondaryMetricAccessor: LENS_LAYERS.metrics.percentage,
          trendlineLayerId: LENS_LAYERS.trend.id,
          trendlineMetricAccessor: LENS_LAYERS.trend.y,
          trendlineTimeAccessor: LENS_LAYERS.trend.x
        }
      },
      title: '',
      visualizationType: 'lnsMetric'
    };
  },
  initialValues
});
exports.AnalyticsCollectionCardWithLens = AnalyticsCollectionCardWithLens;