import _extends from "@babel/runtime/helpers/esm/extends";
import { globalObject } from '@skbkontur/global-object';
export var eventListenersMap = new Map();
export function addResponsiveLayoutListener(mediaQuery, callback) {
  if (eventListenersMap.has(mediaQuery)) {
    addCallbackToMQListener(mediaQuery, callback);
  } else {
    createMQListener(mediaQuery, callback);
  }
  return {
    remove: function remove() {
      removeCallbackFromMQListener(mediaQuery, callback);
    }
  };
}
function addCallbackToMQListener(mediaQuery, callback) {
  var eventListener = eventListenersMap.get(mediaQuery);
  if (eventListener) {
    eventListenersMap.set(mediaQuery, _extends({}, eventListener, {
      listeners: [].concat(eventListener.listeners, [callback])
    }));
  }
}
function createMQListener(mediaQuery, callback) {
  var mql = globalObject.matchMedia == null ? void 0 : globalObject.matchMedia(mediaQuery);
  if (mql) {
    var newMediaQueryInfo = {
      mql: mql,
      listeners: [callback]
    };
    eventListenersMap.set(mediaQuery, newMediaQueryInfo);
    if (mql.addEventListener) {
      mql.addEventListener('change', changeCallback);
    } else {
      mql.addListener(changeCallback);
    }
  }
}
function removeCallbackFromMQListener(mediaQuery, callback) {
  if (eventListenersMap.has(mediaQuery)) {
    var eventListener = eventListenersMap.get(mediaQuery);
    if (eventListener) {
      var newListeners = eventListener.listeners.filter(function (listener) {
        return listener !== callback;
      });
      if (newListeners.length === 0) {
        if (eventListener.mql.removeEventListener) {
          eventListener.mql.removeEventListener('change', changeCallback);
        } else {
          eventListener.mql.removeListener(changeCallback);
        }
        eventListenersMap["delete"](mediaQuery);
        return;
      }
      eventListenersMap.set(mediaQuery, _extends({}, eventListener, {
        listeners: [].concat(newListeners)
      }));
    }
  }
}
export function checkMatches(mediaQuery) {
  var _eventListener$mql$ma;
  if (!globalObject.matchMedia) {
    return false;
  }
  if (!eventListenersMap.has(mediaQuery)) {
    var _globalObject$matchMe;
    return !!((_globalObject$matchMe = globalObject.matchMedia(mediaQuery)) != null && _globalObject$matchMe.matches);
  }
  var eventListener = eventListenersMap.get(mediaQuery);
  return (_eventListener$mql$ma = eventListener == null ? void 0 : eventListener.mql.matches) != null ? _eventListener$mql$ma : false;
}
function changeCallback(e) {
  var eventListener = eventListenersMap.get(e.media);
  if (eventListener) {
    eventListener.listeners.forEach(function (listener) {
      listener(e);
    });
  }
}