export function getClickPoint (event) {
  let pageX = 0;
  let pageY = 0;
  if (event.touches) {
    const touch = event.touches[0];
    ({ pageX, pageY } = touch);
  } else {
    ({ pageX, pageY } = event);
  }
  return {
    pageX,
    pageY
  }
}

export function getAbsoluteCoordinate (ele, event) {
  const { pageX, pageY } = getClickPoint(event)

  const rect = ele.getBoundingClientRect();
  const offsetX = window.pageXOffset || window.scrollX || 0;
  const offsetY = window.pageYOffset || window.scrollY || 0;

  const coordinate = {
    x: pageX - rect.left - offsetX,
    y: pageY - rect.top - offsetY,
  };

  return coordinate
}

export function createSvg (type, attribute, style) {
  const svgEle = document.createElementNS("http://www.w3.org/2000/svg", type);
  for (let key in attribute) {
    svgEle.setAttribute(key, attribute[key])
  }
  if (style) {
    for (let key in style) {
      svgEle.style[key] = style[key]
    }
  }
  return svgEle
}

export function getActualPoint (point, viewport) {
  const { width, height, rotation, scale } = viewport
  let x, y;
  if (rotation === 0) {
    x = point.x * scale;
    y = height - point.y * scale;
  } else if (rotation === 90) {
    x = point.y * scale;
    y = point.x * scale;
  } else if (rotation === 180) {
    x = width - point.x * scale;
    y = point.y * scale;
  } else {
    x = width - point.y * scale;
    y = height - point.x * scale;
  }
  return {
    x,
    y,
  };
}

export function getInitialPoint (point, viewport, s) {
  const { width, height, rotation } = viewport
  let x, y;
  if (rotation === 0) {
    x = point.x / s;
    y = (height - point.y) / s; 
  } else if (rotation === 90) {
    x = point.y / s;
    y = point.x / s;
  } else if (rotation === 180) {
    x =( width - point.x) / s;
    y = point.y / s;
  } else {
    x = (height - point.y) / s
    y = (width - point.x) / s
  }
  return {
    x,
    y,
  };
}

export const getActualRect = (annotation, viewport) => {
  const [x1, y1, x2, y2] = annotation.rect.split(',')

  const start = getActualPoint(
    {
      x: x1,
      y: y1
    },
    viewport,
  )
  const end = getActualPoint(
    {
      x: x2,
      y: y2
    },
    viewport,
  )
  return {
    start,
    end
  }
}

export const calculateRect = (start, end, annotation) => {
  const initRect = rectCalc({ start, end });
  const actualbdwidth = annotation.width || annotation.lineWidth
  return {
    top: initRect.top - actualbdwidth,
    left: initRect.left - actualbdwidth,
    width: initRect.width + actualbdwidth * 2,
    height: initRect.height + actualbdwidth * 2,
  }
}

export const rectCalc = ({ start, end }) => {
  return {
    left: start.x < end.x ? start.x : end.x,
    top: start.y < end.y ? start.y : end.y,
    width: Math.abs(end.x - start.x),
    height: Math.abs(end.y - start.y),
  };
};

export const setCursor = (canvas, cursor) => {
  if (canvas) {
    canvas.style.cursor = cursor;
  }
};
