Liferay.Loader.define("analytics-reports-web@1.0.16/js/state/chartState", ['module', 'exports', 'require', 'frontend-js-react-web$react', '../context/ConnectionContext'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.useChartState = void 0;

    var _react = require("frontend-js-react-web$react");

    var _ConnectionContext = _interopRequireDefault(require("../context/ConnectionContext"));

    function _interopRequireDefault(obj) {
      return obj && obj.__esModule ? obj : { "default": obj };
    }

    function _toConsumableArray(arr) {
      return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _nonIterableSpread();
    }

    function _nonIterableSpread() {
      throw new TypeError("Invalid attempt to spread non-iterable instance");
    }

    function _iterableToArray(iter) {
      if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter);
    }

    function _arrayWithoutHoles(arr) {
      if (Array.isArray(arr)) {
        for (var i = 0, arr2 = new Array(arr.length); i < arr.length; i++) {
          arr2[i] = arr[i];
        }return arr2;
      }
    }

    function ownKeys(object, enumerableOnly) {
      var keys = Object.keys(object);if (Object.getOwnPropertySymbols) {
        var symbols = Object.getOwnPropertySymbols(object);if (enumerableOnly) symbols = symbols.filter(function (sym) {
          return Object.getOwnPropertyDescriptor(object, sym).enumerable;
        });keys.push.apply(keys, symbols);
      }return keys;
    }

    function _objectSpread(target) {
      for (var i = 1; i < arguments.length; i++) {
        var source = arguments[i] != null ? arguments[i] : {};if (i % 2) {
          ownKeys(Object(source), true).forEach(function (key) {
            _defineProperty(target, key, source[key]);
          });
        } else if (Object.getOwnPropertyDescriptors) {
          Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
        } else {
          ownKeys(Object(source)).forEach(function (key) {
            Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
          });
        }
      }return target;
    }

    function _defineProperty(obj, key, value) {
      if (key in obj) {
        Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true });
      } else {
        obj[key] = value;
      }return obj;
    }

    function _slicedToArray(arr, i) {
      return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
    }

    function _nonIterableRest() {
      throw new TypeError("Invalid attempt to destructure non-iterable instance");
    }

    function _iterableToArrayLimit(arr, i) {
      if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
        return;
      }var _arr = [];var _n = true;var _d = false;var _e = undefined;try {
        for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
          _arr.push(_s.value);if (i && _arr.length === i) break;
        }
      } catch (err) {
        _d = true;_e = err;
      } finally {
        try {
          if (!_n && _i["return"] != null) _i["return"]();
        } finally {
          if (_d) throw _e;
        }
      }return _arr;
    }

    function _arrayWithHoles(arr) {
      if (Array.isArray(arr)) return arr;
    }

    var ADD_DATA_SET_ITEMS = 'add-data-keys';
    var CHANGE_TIME_SPAN_KEY = 'change-time-span-key';
    var NEXT_TIME_SPAN = 'next-time-span';
    var PREV_TIME_SPAN = 'previous-time-span';
    var SET_LOADING = 'set-loading';
    var FALLBACK_DATA_SET_ITEM = {
      histogram: [],
      value: null
    };

    var useChartState = function useChartState(_ref) {
      var publishDate = _ref.publishDate,
          timeSpanKey = _ref.timeSpanKey;

      var _useContext = (0, _react.useContext)(_ConnectionContext["default"]),
          validAnalyticsConnection = _useContext.validAnalyticsConnection;

      var _useReducer = (0, _react.useReducer)(reducer, {
        dataSet: {
          histogram: [],
          keyList: [],
          totals: []
        },
        loading: true,
        publishDate: publishDate,
        timeSpanKey: timeSpanKey,
        timeSpanOffset: 0
      }),
          _useReducer2 = _slicedToArray(_useReducer, 2),
          state = _useReducer2[0],
          dispatch = _useReducer2[1];

      return {
        actions: {
          addDataSetItems: function addDataSetItems(payload) {
            return dispatch({
              payload: payload,
              type: ADD_DATA_SET_ITEMS,
              validAnalyticsConnection: validAnalyticsConnection
            });
          },
          changeTimeSpanKey: function changeTimeSpanKey(payload) {
            return dispatch({
              payload: payload,
              type: CHANGE_TIME_SPAN_KEY
            });
          },
          nextTimeSpan: function nextTimeSpan() {
            return dispatch({
              type: NEXT_TIME_SPAN
            });
          },
          previousTimeSpan: function previousTimeSpan() {
            return dispatch({
              type: PREV_TIME_SPAN
            });
          },
          setLoading: function setLoading() {
            return dispatch({
              type: SET_LOADING
            });
          }
        },
        state: state
      };
    };
    /**
     * {
    		"loading": false,
    		"timeSpanOffset": 1,
    		"timeSpanKey": "last-7-days",
    		"dataSet": {
    			"keyList": [
    				"analyticsReportsHistoricalReads",
    				"analyticsReportsHistoricalViews"
    			],
    			"totals": {
    				"analyticsReportsHistoricalReads": 225000,
    				"analyticsReportsHistoricalViews": 144245
    			},
    			"histogram": [
    				{
    					"analyticsReportsHistoricalViews": 5412,
    					"label": "2020-02-02T00:00",
    					"analyticsReportsHistoricalReads": 5000
    				},
    				...
    			]
    		}
    	}
     *
     */

    exports.useChartState = useChartState;

    function reducer(state, action) {
      var nextState;

      switch (action.type) {
        case ADD_DATA_SET_ITEMS:
          nextState = action.payload.keys.reduce(function (state, key) {
            var _action$payload$dataS, _action$payload$dataS2;

            var dataSetItem = (_action$payload$dataS = (_action$payload$dataS2 = action.payload.dataSetItems) === null || _action$payload$dataS2 === void 0 ? void 0 : _action$payload$dataS2[key]) !== null && _action$payload$dataS !== void 0 ? _action$payload$dataS : FALLBACK_DATA_SET_ITEM;
            return addDataSetItem(state, _objectSpread({}, action.payload, {
              dataSetItem: dataSetItem,
              key: key
            }), action.validAnalyticsConnection);
          }, state);
          break;

        case CHANGE_TIME_SPAN_KEY:
          nextState = _objectSpread({}, state, {
            timeSpanKey: action.payload.key,
            timeSpanOffset: 0
          });
          break;

        case NEXT_TIME_SPAN:
          nextState = _objectSpread({}, state, {
            timeSpanOffset: state.timeSpanOffset - 1
          });
          break;

        case PREV_TIME_SPAN:
          nextState = _objectSpread({}, state, {
            timeSpanOffset: state.timeSpanOffset + 1
          });
          break;

        case SET_LOADING:
          nextState = setLoadingState(state);
          break;

        default:
          state = nextState;
          break;
      }

      return nextState;
    }
    /**
     * Declares the state as loading and resets the dataSet histogram values
     */

    function setLoadingState(state) {
      /**
       * The dataSet does not need to be reset
       */
      if (!state.dataSet) {
        return _objectSpread({}, state, {
          loading: true
        });
      }

      var histogram = state.dataSet.histogram.map(function (set) {
        var newSet = {};
        var setArray = Object.entries(set);

        for (var index in setArray) {
          var _setArray$index = _slicedToArray(setArray[index], 2),
              key = _setArray$index[0],
              value = _setArray$index[1];

          if (key === 'label') {
            newSet[key] = value;
          } else {
            newSet[key] = null;
          }
        }

        return newSet;
      });
      var arrayTotals = Object.entries(state.dataSet.totals);
      var totals = {};

      for (var index in arrayTotals) {
        var _arrayTotals$index = _slicedToArray(arrayTotals[index], 1),
            key = _arrayTotals$index[0];

        totals[key] = null;
      }

      var nextState = _objectSpread({}, state, {
        dataSet: _objectSpread({}, state.dataSet, {
          histogram: histogram,
          totals: totals
        }),
        loading: true
      });

      return nextState;
    }

    function mergeDataSets(_ref2) {
      var key = _ref2.key,
          newData = _ref2.newData,
          _ref2$previousDataSet = _ref2.previousDataSet,
          previousDataSet = _ref2$previousDataSet === void 0 ? {
        histogram: [],
        keyList: [],
        totals: []
      } : _ref2$previousDataSet,
          publishDate = _ref2.publishDate,
          timeSpanComparator = _ref2.timeSpanComparator,
          validAnalyticsConnection = _ref2.validAnalyticsConnection;
      var resultDataSet = {
        keyList: [].concat(_toConsumableArray(previousDataSet.keyList), [key]),
        totals: _objectSpread({}, previousDataSet.totals, _defineProperty({}, key, newData.value))
      };
      var publishDateObject = new Date(publishDate);
      var newFormattedHistogram = newData.histogram.map(function (h) {
        var _ref4;

        var valueDataObject = new Date(h.key);

        if (valueDataObject < publishDateObject && publishDateObject - valueDataObject > timeSpanComparator || !validAnalyticsConnection) {
          var _ref3;

          return _ref3 = {}, _defineProperty(_ref3, key, null), _defineProperty(_ref3, "label", h.key), _ref3;
        }

        return _ref4 = {}, _defineProperty(_ref4, key, h.value), _defineProperty(_ref4, "label", h.key), _ref4;
      });

      if (newFormattedHistogram.length === 0) {
        return _objectSpread({}, resultDataSet, {
          histogram: previousDataSet.histogram
        });
      }

      var start = 0;
      var mergeHistogram = [];

      while (start < newData.histogram.length) {
        if (!previousDataSet.histogram[start]) {
          mergeHistogram.push(_objectSpread({}, newFormattedHistogram[start]));
        } else if (newFormattedHistogram[start].label === previousDataSet.histogram[start].label) {
          mergeHistogram.push(_objectSpread({}, newFormattedHistogram[start], {}, previousDataSet.histogram[start]));
        }

        start = start + 1;
      }

      resultDataSet.histogram = mergeHistogram;
      return resultDataSet;
    }
    /**
     * Adds dataSetItem to the dataSet
     *
     * payload = {
     * 	dataSet: {
     * 		histogram: Array<{
     *			key: string, // '2020-01-24T00:00'
     *			value: number
     * 		}>
     * 		values: number
     * 	},
     * 	key: string,
     *  timeSpanComparator: number,
     * }
     */

    function addDataSetItem(state, payload, validAnalyticsConnection) {
      /**
       * The dataSetItem is recognized as substitutive when the
       * previous state was in loading state.
       */
      var previousDataSet = state.loading === true ? undefined : state.dataSet;
      return _objectSpread({}, state, {
        dataSet: mergeDataSets({
          key: payload.key,
          newData: payload.dataSetItem,
          previousDataSet: previousDataSet,
          publishDate: state.publishDate,
          timeSpanComparator: payload.timeSpanComparator,
          validAnalyticsConnection: validAnalyticsConnection
        }),
        loading: false
      });
    }
    //# sourceMappingURL=chartState.js.map
  }
});
//# sourceMappingURL=chartState.js.map