import { markRaw } from 'vue'
import type { RegionMask } from '@/types/mosaic'

export function createRegionMask(width: number, height: number, runs: number[]): RegionMask {
  return markRaw({ width, height, runs: markRaw(Uint32Array.from(runs)) })
}

export function forEachMaskRun(
  mask: RegionMask,
  callback: (y: number, xStart: number, xEnd: number) => void,
): void {
  for (let index = 0; index < mask.runs.length; index += 3) {
    callback(mask.runs[index] ?? 0, mask.runs[index + 1] ?? 0, mask.runs[index + 2] ?? 0)
  }
}

export function buildOccupancy(width: number, height: number, masks: RegionMask[]): Uint8Array {
  const occupancy = new Uint8Array(width * height)
  for (const mask of masks) {
    forEachMaskRun(mask, (y, xStart, xEnd) => {
      occupancy.fill(1, y * width + xStart, y * width + xEnd + 1)
    })
  }
  return occupancy
}

export function maskContains(mask: RegionMask, x: number, y: number): boolean {
  for (let index = 0; index < mask.runs.length; index += 3) {
    const runY = mask.runs[index] ?? -1
    if (runY > y) return false
    if (runY === y && x >= (mask.runs[index + 1] ?? 0) && x <= (mask.runs[index + 2] ?? -1)) {
      return true
    }
  }
  return false
}
