'use strict';

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

var isNum = _interopDefault(require('./isNum'));
var isFun = _interopDefault(require('./isFun'));
var isHTMLElement = _interopDefault(require('./isHTMLElement'));
var getClientSize = _interopDefault(require('./getClientSize'));
var getPageSize = _interopDefault(require('./getPageSize'));
var getScrollPosition = _interopDefault(require('./getScrollPosition'));
var requestAnimationFrame = _interopDefault(require('./requestAnimationFrame'));

/**
 * 滚动到指定位置
 * @param {number} height
 * @param {Object} options
 *
 * // 页面滚动
 * scrollTo(200);
 * // 取消动画
 * scrollTo(500, { animation: false });
 * // 快速动画
 * scrollTo(500, { speed: 3 });
 * // 窗口滚动
 * scrollTo(500, { element: document.querySelector('#container') });
 * // 完成时回调
 * scrollTo(500, { onDone: () => { do sth. } });
 */
function scrollTo(height, options) {
  if (!isNum(height)) {
    if (isFun(options.onDone)) {
      options.onDone();
    }

    return;
  }

  if (height < 0) height = 0;
  options = options || {};
  var element = isHTMLElement(options.element) ? options.element : null;
  var animation = options.animation !== false;
  var speed = isNum(options.speed) ? options.speed : 6;

  if (animation) {
    var scrollTop;
    var offsetHeight;
    var scrollHeight;

    if (element) {
      scrollTop = element.scrollTop;
      offsetHeight = element.offsetHeight;
      scrollHeight = element.scrollHeight;
    } else {
      scrollTop = getScrollPosition().scrollTop;
      offsetHeight = getClientSize().clientHeight;
      scrollHeight = getPageSize().pageHeight;
    }

    var max = scrollHeight - offsetHeight;
    var h = height > max ? max : height;
    var diff = Math.abs(scrollTop - h);
    var step = diff > 1 ? Math.ceil(diff / speed) : diff;
    var to = scrollTop > h ? scrollTop - step : scrollTop + step;
    (element || window).scrollTo(0, to);

    if (diff > 1) {
      requestAnimationFrame(function () {
        return scrollTo(height, options);
      });
    } else {
      if (isFun(options.onDone)) {
        options.onDone();
      }
    }
  } else {
    (element || window).scrollTo(0, height);

    if (isFun(options.onDone)) {
      options.onDone();
    }
  }
}

module.exports = scrollTo;
