'use strict';

function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }

var getClientSize = _interopDefault(require('./getClientSize'));
var isFun = _interopDefault(require('./isFun'));

/**
 * 监听窗口变化，H5判断软键盘是否打开
 * @param {Function} callback
 * @param {boolean} immediate
 * @returns
 *
 * 结合offWindowResize()方法一起使用
 * // 开启监听
 * const windowResizeHandler = onWindowResize(({isUp, isDown}) => {
 *   console.log(isUp, isDown);
 * });
 *
 * // 关闭监听
 * windowResizeHandler.off()
 * // or
 * offWindowResize(windowResizeHandler);
 */
function onWindowResize(callback, immediate) {
  var _getClientSize = getClientSize(),
      originWidth = _getClientSize.clientWidth,
      originHeight = _getClientSize.clientHeight;

  var prevWidth = originWidth;
  var prevHeight = originHeight;

  var resizeHandler = function resizeHandler() {
    var _getClientSize2 = getClientSize(),
        clientWidth = _getClientSize2.clientWidth,
        clientHeight = _getClientSize2.clientHeight;

    var resizeInfo = {
      isUp: clientHeight < prevHeight,
      isDown: clientHeight > prevHeight,
      isShowKeyboard: clientHeight < originHeight - 10,
      width: clientWidth,
      height: clientHeight,
      prevWidth: prevWidth,
      prevHeight: prevHeight,
      originWidth: originWidth,
      originHeight: originHeight
    };
    prevWidth = clientWidth;
    prevHeight = clientHeight;
    if (isFun(callback)) callback(resizeInfo);
  };

  if (immediate) resizeHandler();
  window.addEventListener('resize', resizeHandler);

  resizeHandler.off = function () {
    window.removeEventListener('resize', resizeHandler);
  };

  return resizeHandler;
}

module.exports = onWindowResize;
