Liferay.Loader.define("analytics-reports-web@1.0.39/js/context/ChartStateContext", ['module', 'exports', 'require', 'frontend-js-react-web$react', './ConnectionContext'], function (module, exports, require) {
  var define = undefined;
  var global = window;
  {
    function _typeof(obj) {
      "@babel/helpers - typeof";
      if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") {
        _typeof = function _typeof(obj) {
          return typeof obj;
        };
      } else {
        _typeof = function _typeof(obj) {
          return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
        };
      }return _typeof(obj);
    }

    Object.defineProperty(exports, "__esModule", {
      value: true
    });
    exports.useDateTitle = useDateTitle;
    exports.useIsPreviousPeriodButtonDisabled = useIsPreviousPeriodButtonDisabled;
    exports.usePreviousTimeSpan = exports.useSetLoading = exports.useNextTimeSpan = exports.useChartState = exports.useChangeTimeSpanKey = exports.useAddDataSetItems = exports.ChartStateContextProvider = void 0;

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

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

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

    function _getRequireWildcardCache() {
      if (typeof WeakMap !== "function") return null;var cache = new WeakMap();_getRequireWildcardCache = function _getRequireWildcardCache() {
        return cache;
      };return cache;
    }

    function _interopRequireWildcard(obj) {
      if (obj && obj.__esModule) {
        return obj;
      }if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") {
        return { default: obj };
      }var cache = _getRequireWildcardCache();if (cache && cache.has(obj)) {
        return cache.get(obj);
      }var newObj = {};var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor;for (var key in obj) {
        if (Object.prototype.hasOwnProperty.call(obj, key)) {
          var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null;if (desc && (desc.get || desc.set)) {
            Object.defineProperty(newObj, key, desc);
          } else {
            newObj[key] = obj[key];
          }
        }
      }newObj.default = obj;if (cache) {
        cache.set(obj, newObj);
      }return newObj;
    }

    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 _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;
    }

    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;
    }

    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 INITIAL_STATE = {
      dataSet: {
        histogram: [],
        keyList: [],
        totals: []
      },
      loading: true,
      publishDate: null,
      timeRange: null,
      timeSpanKey: null,
      timeSpanOffset: 0
    };
    var FALLBACK_DATA_SET_ITEM = {
      histogram: [],
      value: null
    };
    var ChartStateContext = /*#__PURE__*/(0, _react.createContext)(INITIAL_STATE);

    var ChartStateContextProvider = function ChartStateContextProvider(_ref) {
      var children = _ref.children,
          publishDate = _ref.publishDate,
          timeRange = _ref.timeRange,
          timeSpanKey = _ref.timeSpanKey;
      var stateAndDispatch = (0, _react.useReducer)(reducer, _objectSpread(_objectSpread({}, INITIAL_STATE), {}, {
        publishDate: publishDate,
        timeRange: timeRange,
        timeSpanKey: timeSpanKey
      }));
      return (/*#__PURE__*/_react.default.createElement(ChartStateContext.Provider, {
          value: stateAndDispatch
        }, children)
      );
    };

    exports.ChartStateContextProvider = ChartStateContextProvider;

    var useAddDataSetItems = function useAddDataSetItems() {
      var _useContext = (0, _react.useContext)(ChartStateContext),
          _useContext2 = _slicedToArray(_useContext, 2),
          dispatch = _useContext2[1];

      var _useContext3 = (0, _react.useContext)(_ConnectionContext.default),
          validAnalyticsConnection = _useContext3.validAnalyticsConnection;

      return (0, _react.useCallback)(function (payload) {
        return dispatch({
          payload: payload,
          type: ADD_DATA_SET_ITEMS,
          validAnalyticsConnection: validAnalyticsConnection
        });
      }, [dispatch, validAnalyticsConnection]);
    };

    exports.useAddDataSetItems = useAddDataSetItems;

    var useChangeTimeSpanKey = function useChangeTimeSpanKey() {
      var _useContext4 = (0, _react.useContext)(ChartStateContext),
          _useContext5 = _slicedToArray(_useContext4, 2),
          dispatch = _useContext5[1];

      return function (payload) {
        return dispatch({
          payload: payload,
          type: CHANGE_TIME_SPAN_KEY
        });
      };
    };

    exports.useChangeTimeSpanKey = useChangeTimeSpanKey;

    var useChartState = function useChartState() {
      var _useContext6 = (0, _react.useContext)(ChartStateContext),
          _useContext7 = _slicedToArray(_useContext6, 1),
          state = _useContext7[0];

      return state;
    };

    exports.useChartState = useChartState;

    function useDateTitle() {
      var _useContext8 = (0, _react.useContext)(ChartStateContext),
          _useContext9 = _slicedToArray(_useContext8, 1),
          state = _useContext9[0];

      var histogram = state.dataSet.histogram;
      var timeRange = state.timeRange;

      if (histogram.length) {
        var firstDateLabel = histogram[0].label;
        var lastDateLabel = histogram[histogram.length - 1].label;
        return {
          firstDate: new Date(firstDateLabel),
          lastDate: new Date(lastDateLabel)
        };
      } else {
        return {
          firstDate: new Date(timeRange.startDate),
          lastDate: new Date(timeRange.endDate)
        };
      }
    }

    function useIsPreviousPeriodButtonDisabled() {
      var _useContext10 = (0, _react.useContext)(ChartStateContext),
          _useContext11 = _slicedToArray(_useContext10, 1),
          state = _useContext11[0];

      var histogram = state.dataSet.histogram;
      var publishDate = state.publishDate;

      if (histogram.length) {
        var firstDateLabel = histogram[0].label;
        var firstDate = new Date(firstDateLabel);
        var publishedDate = new Date(publishDate);
        return firstDate < publishedDate;
      }

      return true;
    }

    var useNextTimeSpan = function useNextTimeSpan() {
      var _useContext12 = (0, _react.useContext)(ChartStateContext),
          _useContext13 = _slicedToArray(_useContext12, 2),
          dispatch = _useContext13[1];

      return function () {
        return dispatch({
          type: NEXT_TIME_SPAN
        });
      };
    };

    exports.useNextTimeSpan = useNextTimeSpan;

    var useSetLoading = function useSetLoading() {
      var _useContext14 = (0, _react.useContext)(ChartStateContext),
          _useContext15 = _slicedToArray(_useContext14, 2),
          dispatch = _useContext15[1];

      return (0, _react.useCallback)(function () {
        return dispatch({
          type: SET_LOADING
        });
      }, [dispatch]);
    };

    exports.useSetLoading = useSetLoading;

    var usePreviousTimeSpan = function usePreviousTimeSpan() {
      var _useContext16 = (0, _react.useContext)(ChartStateContext),
          _useContext17 = _slicedToArray(_useContext16, 2),
          dispatch = _useContext17[1];

      return function () {
        return dispatch({
          type: PREV_TIME_SPAN
        });
      };
    };
    /**
     * {
    		"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.usePreviousTimeSpan = usePreviousTimeSpan;

    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(_objectSpread({}, action.payload), {}, {
              dataSetItem: dataSetItem,
              key: key
            }), action.validAnalyticsConnection);
          }, state);
          break;

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

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

        case PREV_TIME_SPAN:
          nextState = _objectSpread(_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(_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(_objectSpread({}, state), {}, {
        dataSet: _objectSpread(_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(_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(_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(_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(_objectSpread({}, state), {}, {
        dataSet: mergeDataSets({
          key: payload.key,
          newData: payload.dataSetItem,
          previousDataSet: previousDataSet,
          publishDate: state.publishDate,
          timeSpanComparator: payload.timeSpanComparator,
          validAnalyticsConnection: validAnalyticsConnection
        }),
        loading: false
      });
    }
    //# sourceMappingURL=ChartStateContext.js.map
  }
});
//# sourceMappingURL=ChartStateContext.js.map