///|
priv struct Projection {
  coefficients : FixedArray[Double]
}

///|
fn Point::distance_squared(a : Point, b : Point) -> Double {
  let dx = a.x - b.x
  let dy = a.y - b.y
  dx * dx + dy * dy
}

///|
fn turn(a : Point, b : Point, c : Point) -> Double {
  (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x)
}

///|
fn quad_area(points : Array[Point]) -> Double {
  (
    points[0].x * points[1].y -
    points[0].y * points[1].x +
    (points[1].x * points[2].y - points[1].y * points[2].x) +
    (points[2].x * points[3].y - points[2].y * points[3].x) +
    (points[3].x * points[0].y - points[3].y * points[0].x)
  ) /
  2.0
}

///|
fn convex_quad(points : Array[Point]) -> Bool {
  if points.length() != 4 {
    return false
  }
  for i in 0..<4 {
    if !(turn(points[i], points[(i + 1) % 4], points[(i + 2) % 4]) > 0.01) {
      return false
    }
  }
  true
}

///|
fn projection(from : Array[Point], to : Array[Point]) -> Projection? {
  if !convex_quad(from) || !convex_quad(to) {
    return None
  }
  let matrix : Array[Array[Double]] = []
  for i in 0..<4 {
    let x = from[i].x
    let y = from[i].y
    let a = to[i].x
    let b = to[i].y
    matrix.push([x, y, 1.0, 0.0, 0.0, 0.0, -a * x, -a * y, a])
    matrix.push([0.0, 0.0, 0.0, x, y, 1.0, -b * x, -b * y, b])
  }
  for column in 0..<8 {
    let mut pivot = column
    for row in (column + 1)..<8 {
      if matrix[row][column].abs() > matrix[pivot][column].abs() {
        pivot = row
      }
    }
    let divisor = matrix[pivot][column]
    if !(divisor.abs() > 0.000000001) {
      return None
    }
    let scale_row = matrix[pivot]
    matrix[pivot] = matrix[column]
    matrix[column] = scale_row
    for j in column..<9 {
      scale_row[j] /= divisor
    }
    for row in 0..<8 {
      if row == column {
        continue
      }
      let eliminate = matrix[row][column]
      for j in column..<9 {
        matrix[row][j] -= eliminate * scale_row[j]
      }
    }
  }
  let coefficients = FixedArray::makei(8, i => matrix[i][8])
  Some({ coefficients, })
}

///|
fn Projection::map(self : Projection, x : Double, y : Double) -> Point? {
  let h = self.coefficients
  let scale = h[6] * x + h[7] * y + 1.0
  if !(scale.abs() > 0.00000001) {
    return None
  }
  Some({
    x: (h[0] * x + h[1] * y + h[2]) / scale,
    y: (h[3] * x + h[4] * y + h[5]) / scale,
  })
}

///|
fn projected_gray(
  image : GrayImage,
  transform : Projection,
  x : Double,
  y : Double,
) -> Double? {
  match transform.map(x, y) {
    Some(p) => image.interpolate(p.x, p.y)
    None => None
  }
}

///|
fn patch_mean(
  image : GrayImage,
  transform : Projection,
  center : Point,
  radius : Int32,
) -> Double? {
  let mut sum = 0.0
  let mut count = 0
  for row in -radius..<(radius + 1) {
    for col in -radius..<(radius + 1) {
      guard projected_gray(
          image,
          transform,
          center.x + col.to_double(),
          center.y + row.to_double(),
        )
        is Some(value) else {
        return None
      }
      sum += value
      count += 1
    }
  }
  Some(sum / count.to_double())
}

///|
fn warp(
  source : GrayImage,
  transform : Projection,
  width : Int32,
  height : Int32,
) -> GrayImage raise MarkError {
  let count = checked_pixels(width, height)
  let pixels = FixedArray::makei(count, i => {
    let value = projected_gray(
      source,
      transform,
      (i % width).to_double(),
      (i / width).to_double(),
    ).unwrap_or(255.0)
    clamp_int(value.round().to_int(), 0, 255).to_byte()
  })
  GrayImage::new(width, height, Bytes::from_array(pixels[:]))
}