// Pure MoonBit port of stb_image_write v1.19 TGA writer
// (uncompressed and RLE truecolor / grayscale, 8/15/16/24/32-bit).

///|
/// Byte-wise `memcmp(a, b) == 0` over `comp` channels.
fn stbiw_bytes_equal(data : Bytes, a : Int, b : Int, comp : Int) -> Bool {
  for i = 0; i < comp; i = i + 1 {
    if data[a + i] != data[b + i] {
      return false
    }
  }
  true
}

///|
/// Write the 18-byte TGA header.
fn stbiw_tga_header(
  w : StbiwWriter,
  width : Int,
  height : Int,
  image_type : Int,
  colorbytes : Int,
  has_alpha : Bool,
) -> Unit {
  w.write_u8(0) // id length
  w.write_u8(0) // colormap type
  w.write_u8(image_type)
  w.write_u16le(0) // colormap first
  w.write_u16le(0) // colormap length
  w.write_u8(0) // colormap entry size
  w.write_u16le(0) // x origin
  w.write_u16le(0) // y origin
  w.write_u16le(width)
  w.write_u16le(height)
  w.write_u8((colorbytes + (if has_alpha { 1 } else { 0 })) * 8)
  w.write_u8(if has_alpha { 8 } else { 0 })
}

///|
/// Encode 8-bit pixels as a TGA file in memory.
///
/// `options.tga_with_rle` selects image types 10/11 instead of 2/3.
pub fn stbi_write_tga_to_memory(
  width : Int,
  height : Int,
  comp : Int,
  data : Bytes,
  stride_in_bytes? : Int = 0,
  options? : StbiwOptions,
) -> Bytes? {
  let opts = match options {
    Some(o) => o
    None => StbiwOptions::default()
  }
  let stride = match stbiw_resolve_byte_stride(
    width,
    height,
    comp,
    stride_in_bytes,
    data.length(),
  ) {
    Some(s) => s
    None => return None
  }
  let has_alpha = comp == 2 || comp == 4
  let colorbytes = if has_alpha { comp - 1 } else { comp }
  // 3 = grayscale (1 or 2 channels), 2 = truecolor
  let format = if colorbytes < 2 { 3 } else { 2 }
  let w = StbiwWriter::new(capacity=18 + width * height * comp)
  if !opts.tga_with_rle {
    stbiw_tga_header(w, width, height, format, colorbytes, has_alpha)
    stbiw_write_pixels(
      w,
      data,
      width,
      height,
      comp,
      stride,
      opts.flip_vertically,
      -1,
      -1,
      has_alpha,
      0,
      false,
    )
    return Some(w.to_bytes())
  }
  stbiw_tga_header(w, width, height, format + 8, colorbytes, has_alpha)
  let mut j = if opts.flip_vertically { 0 } else { height - 1 }
  let j_end = if opts.flip_vertically { height } else { -1 }
  let jdir = if opts.flip_vertically { 1 } else { -1 }
  while j != j_end {
    let row = j * stride
    let mut i = 0
    while i < width {
      let begin = row + i * comp
      let mut diff = true
      let mut len = 1
      if i < width - 1 {
        len = 2
        diff = !stbiw_bytes_equal(data, begin, row + (i + 1) * comp, comp)
        if diff {
          let mut prev = begin
          let mut k = i + 2
          while k < width && len < 128 {
            if !stbiw_bytes_equal(data, prev, row + k * comp, comp) {
              prev += comp
              len += 1
            } else {
              len -= 1
              break
            }
            k += 1
          }
        } else {
          let mut k = i + 2
          while k < width && len < 128 {
            if stbiw_bytes_equal(data, begin, row + k * comp, comp) {
              len += 1
            } else {
              break
            }
            k += 1
          }
        }
      }
      if diff {
        w.write_u8(len - 1)
        for k = 0; k < len; k = k + 1 {
          stbiw_write_pixel(
            w,
            data,
            begin + k * comp,
            -1,
            comp,
            has_alpha,
            false,
          )
        }
      } else {
        w.write_u8(len - 129)
        stbiw_write_pixel(w, data, begin, -1, comp, has_alpha, false)
      }
      i += len
    }
    j += jdir
  }
  Some(w.to_bytes())
}