import { isWeex } from 'universal-env';

declare global {
  function  __weex_require__(s: string): any
}

export const px2rem = function(dur: number) {
  const FULL_WIDTH = 750;
  const clientWidth = document.documentElement.clientWidth;
  return isWeex ? dur : (dur * FULL_WIDTH) / clientWidth;
};

export const rem2px = function(dur: number) {
  const FULL_WIDTH = 750;
  const clientWidth = document.documentElement.clientWidth;
  return isWeex ? dur : `${(dur * clientWidth) / FULL_WIDTH}px`;
};

function transferObject2rem(obj: any) {
  Object.keys(obj).forEach(key => {
    obj[key] = px2rem(obj[key]);
  });
}

export function getComponentRect(node: any, isRem: boolean, callback) {
  const isViewport = node === 'viewport';
  const isCallback = typeof isRem === 'function';
  const isRealRem = isCallback ? false : isRem;
  const realCallback = isCallback ? isRem : callback;

  if (isWeex) {
    const dom = __weex_require__('@weex-module/dom');
    dom.getComponentRect(isViewport ? node : node.ref, option => {
      realCallback(option.size);
    });
  } else {
    const { clientHeight, clientWidth, clientTop, clientLeft } = document.documentElement;
    const viewportDOM = isViewport ? {} : node.getBoundingClientRect();
    let size = isViewport
      ? {
          height: clientHeight,
          width: clientWidth,
          top: clientTop,
          left: clientLeft,
          bottom: clientHeight + clientTop,
          right: clientWidth + clientLeft
        }
      : {
          height: viewportDOM.height,
          width: viewportDOM.width,
          top: viewportDOM.top,
          left: viewportDOM.left,
          bottom: viewportDOM.bottom,
          right: viewportDOM.right
        };
    if (isRealRem) {
      transferObject2rem(size);
    }
    realCallback(size);
  }
}

export function scrollIntoView(node: any, container: any, animated = true, offset = 0) {
  if (isWeex) {
    const dom = __weex_require__('@weex-module/dom');
    dom.scrollToElement(node, { offset, animated });
  } else {
    const offsetTop = node.offsetTop;
    container.scrollTop = offsetTop > offset ? offsetTop + offset : offsetTop;
  }
}
