/**
 * Copyright (c) 2021 Dominic Masters
 * 
 * This software is released under the MIT License.
 * https://opensource.org/licenses/MIT
 */

#include "aabb.h"

bool aabbPoint2D(
  float pointX, float pointY,
  float x, float y, float width, float height,
  aabbpointhit2d_t *hit
) {

  float dx, px, sx, halfWidth;
  float dy, py, sy, halfHeight;
  
  if(hit == NULL) {
    // Check X Axis, are we outside the box
    if(pointX < x || pointY < y) return false;
    if(pointX > x+width || pointY > y+height) return false;
    return true;
  }

  halfWidth = width / 2;
  halfHeight = height / 2;
  x += halfWidth;
  y += halfHeight;

  dx = pointX - x;
  px = halfWidth - mathAbs(dx);
  if(px <= 0) return false;

  dy = pointY - y;
  py = halfHeight - mathAbs(dy);
  if(py <= 0) return false;

  if(px < py) {
    sx = mathSign(dx);
    // float deltaX = px *sx;
    hit->normalX = sx;
    hit->normalY = 0;
    hit->hitX = x + (halfWidth * sx);
    hit->hitY = pointY;
  } else {
    sy = mathSign(dy);
    // float deltaY = py * sy;
    hit->normalX = 0;
    hit->normalY = sy;
    hit->hitX = pointX;
    hit->hitY = x + (halfHeight * sy);
  }

  return true;
}

bool aabbVector2D(
  float x, float y,
  float vx, float vy,
  float bx, float by, float width, float height,
  aabbvectorhit2d_t *hit
) {
  // float halfWidth = width / 2.0;
  // float halfHeight = height / 2.0;
  // float paddingX = 0;
  // float paddingY = 0;

  // float scaleX = 1.0 / vx;
  // float scaleY = 1.0 / vy;
  // float signX = mathSign(scaleX);
  // float signY = mathSign(scaleY);

  // float nearTimeX = (bx - signX * (halfWidth + paddingX) - bx) * scaleX;
  // float nearTimeY = (by - signY * (halfHeight + paddingY) - by) * scaleY;
  // float farTimeX = (bx + signX * (halfWidth + paddingX) - bx) * scaleX;
  // float farTimeY = (by + signY * (halfHeight + paddingY) - by) * scaleY;

  // if(nearTimeX > farTimeY || nearTimeY > farTimeX) return false;

  // float nearTime = nearTimeX > nearTimeY ? nearTimeX : nearTimeY;
  // float farTime = farTimeX < farTimeY ? farTimeX : farTimeY;
  // if (nearTime >= 1 || farTime <= 0) return false;

  // hit->time = mathClamp(nearTime, 0, 1);
  // if(nearTimeX > nearTimeY) {
  //   hit->normalX = -signX;
  //   hit->normalY = 0;
  // } else {
  //   hit->normalX = 0;
  //   hit->normalY = -signY;
  // }

  // float deltaX = (1.0 - hit->time) * -vx;
  // float deltaY = (1.0 - hit->time) * -vy;
  // hit->hitX = bx + deltaX * hit->time;
  // hit->hitY = by + deltaY * hit->time;

  return true;
}