/**
 * Get `event.target` relative position to `element`. Provide `element` paddings
 * @param {Event} event
 * @param {HTMLElement} element
 * @returns {object}
 */
export default function getRelativePosition (event, element) {
  const rect = element.getBoundingClientRect();
  /* istanbul ignore next */
  const scrollTop = document.documentElement.scrollTop
    ? document.documentElement.scrollTop
    : document.body.scrollTop;
  /* istanbul ignore next */
  const scrollLeft = document.documentElement.scrollLeft
    ? document.documentElement.scrollLeft
    : document.body.scrollLeft;
  const elementLeft = rect.left + scrollLeft;
  const elementTop = rect.top + scrollTop;
  let x = 0;
  let y = 0;
  if (event.type.indexOf('mouse') === 0) {
    const mouseEvent = event;
    x = mouseEvent.pageX - elementLeft;
    y = mouseEvent.pageY - elementTop;
  } else if (event.type.indexOf('touch') === 0) {
    const touchEvent = event;
    x = touchEvent.targetTouches[0].pageX - elementLeft;
    y = touchEvent.targetTouches[0].pageY - elementTop;
  }
  x = x < 0 ? 0 : x;
  y = y < 0 ? 0 : y;
  x = x > rect.width ? rect.width : x;
  y = y > rect.height ? rect.height : y;
  const style = window.getComputedStyle(element);
  return {
    x,
    y,
    pl: parseFloat(style.paddingLeft),
    pt: parseFloat(style.paddingTop)
  };
}
