// SSI - Simple Scanline Image
// A partial image consisting of exactly one horizontal line per row.
// All pixels are of the same color.

// The important values are y1 and data
persistable sclass SSI is HasBounds, G2Drawable {
  // core value (mandatory): first row occupied
  settable int y1;
  
  // core value (mandatory): x coordinates per row
  // x_left is inclusive, x_right is exclusive
  //
  // Order in array:
  //   x_left at y1, x_right at y1,
  //   x_left at y1+1, x_right at y1+1, ,,,
  settable int[] data;

  // Color in 15 bit
  settable short hi15color;
  
  *(int *y1, int y2) {
    data = newIntArrayOrNull((y2-y1)*2);
  }
  
  void set(int y, int xLeft, int xRight) {
    data[(y-y1)*2] = xLeft;
    data[(y-y1)*2+1] = xRight;
  }
  
  // bounds can be calculated quickly from core values
  public simplyCached Rect bounds() {
    int x1 = Int.MAX_VALUE, x2 = 0;
    for (int i = 0; i < l(data); i += 2) {
      x1 = min(x1, data[i]);
      x2 = max(x2, data[i+1]);
    }
    ret rectFromPoints(x1, y1, x2, y2());
  }
  
  int height() { ret l(data)/2; }
  int y2() { ret y1+height(); }
  
  bool contains(Pt p) { ret contains(p.x, p.y); }
  bool contains(int x, int y) {
    if (y < y1) false;
    int i = (y-y1)*2;
    if (i >= l(data)) false;
    ret x >= data[i] && x < data[i+1];
  }
  
  Color color() {
    ret main hi15color(hi15color);
  }
  
  selfType color(RGB color) {
    ret hi15color(rgbToHi15(color));
  }
  
  public void drawOn(Graphics2D g) {
    g.setColor(color());
    int h = height();
    for y to h: {
      int x1 = data[y*2], x2 = data[y*2+1];
      if (x1 < x2)
        g.drawLine(x1, y1+y, x2-1, y1+y);
    }
  }
}