"use strict";var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault").default;exports.__esModule = true;exports.useResponsiveLayout = useResponsiveLayout;var _extends3 = _interopRequireDefault(require("@babel/runtime/helpers/extends"));
var _react = require("react");

var _ThemeContext = require("../../lib/theming/ThemeContext");


var _ResponsiveLayoutEvents = require("./ResponsiveLayoutEvents");

function useResponsiveLayout(_temp)

{var _ref = _temp === void 0 ? {} : _temp,customMediaQueries = _ref.customMediaQueries;
  var theme = (0, _react.useContext)(_ThemeContext.ThemeContext);

  var allMediaQueries = Object.entries((0, _extends3.default)({
    isMobile: theme.mobileMediaQuery },
  customMediaQueries)
  ).map(function (_ref2) {var key = _ref2[0],value = _ref2[1];return {
      flag: key,
      query: value,
      ref: /*#__PURE__*/(0, _react.createRef)()
    };});

  var getLayoutFromGlobal = function getLayoutFromGlobal() {
    return allMediaQueries.reduce(
      function (result, mediaQuery) {var _Object$assign;return Object.assign(result, (_Object$assign = {}, _Object$assign[mediaQuery.flag] = (0, _ResponsiveLayoutEvents.checkMatches)(mediaQuery.query), _Object$assign));},
      {}
    );
  };

  var _useState = (0, _react.useState)(getLayoutFromGlobal()),state = _useState[0],setState = _useState[1];

  var prepareMediaQueries = (0, _react.useCallback)(function () {
    if (!theme) {
      return;
    }

    allMediaQueries.forEach(
      function (mediaQuery) {return (
          mediaQuery.ref.current = (0, _ResponsiveLayoutEvents.addResponsiveLayoutListener)(mediaQuery.query, checkLayoutsMediaQueries));}
    );

    // Checking for SSR use case
    var globalLayout = getLayoutFromGlobal();
    var hasChangedQuery = Object.entries(globalLayout).find(function (_ref3) {var key = _ref3[0],value = _ref3[1];return state[key] !== value;});

    if (hasChangedQuery) {
      setState(globalLayout);
    }
  }, [theme]);

  var checkLayoutsMediaQueries = (0, _react.useCallback)(
    function (e) {
      if (!theme) {
        return;
      }

      allMediaQueries.forEach(function (mediaQuery) {
        if (e.media === mediaQuery.query) {
          setState(function (prevState) {var _extends2;return (0, _extends3.default)({},
            prevState, (_extends2 = {}, _extends2[
            mediaQuery.flag] = e.matches, _extends2));}
          );
        }
      });
    },
    [theme]
  );

  (0, _react.useEffect)(function () {
    prepareMediaQueries();

    return function () {
      allMediaQueries.forEach(function (mediaQuery) {var _mediaQuery$ref$curre;return (_mediaQuery$ref$curre = mediaQuery.ref.current) == null ? void 0 : _mediaQuery$ref$curre.remove();});
    };
  }, []);

  return state;
}