package csa.tiletools.worldgen.mapgen.miny.render;

import csa.tiletools.worldgen.mapgen.miny.render.BB.BBRect;
import csa.tiletools.worldgen.mapgen.miny.render.BB.BoundingBox;
import csa.tiletools.worldgen.mapgen.processing.CSAProcessing;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.util.Vector;

public class Renderer
{
  public int[] pixels;

  //private CSAImage _img;
  private Vector<Drawable> shapes;
  private int totalRender;

  int width;
  int height;

  public Renderer(int w, int h)
  {
    width = w;
    height = h;
    this.pixels = new int[width*height];
    this.totalRender = 0;
    this.shapes = new Vector();
  }

  public void setBackground(int paramInt)
  {
    for (int i = 0; i < width * height; i++) {
          pixels[i] = paramInt;
      }
  }

  public BufferedImage getImage()
  {
    BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
    WritableRaster wr = image.getRaster();
    wr.setDataElements(0, 0, width, height, pixels);
    return image;
  }

  public void add(Drawable paramDrawable)
  {
    paramDrawable.setRenderer(this);
    this.shapes.add(paramDrawable);
  }

  public boolean finished()
  {
    return this.totalRender >= this.shapes.size();
  }

  public float getProgress()
  {
    return this.totalRender / this.shapes.size();
  }

  public void renderAll()
  {
    while (this.totalRender < this.shapes.size())
    {
      Drawable localDrawable = (Drawable)this.shapes.get(this.totalRender);
      BoundingBox localBoundingBox = localDrawable.getBoundingBox();
      BBRect localBBRect = localBoundingBox.getExtends();
      int j = localDrawable.blendMode;
      int k = CSAProcessing.max(0, localBBRect.left);
      int m = CSAProcessing.max(0, localBBRect.top);
      int n = CSAProcessing.min(width - 1, localBBRect.right);
      int i1 = CSAProcessing.min(height - 1, localBBRect.bottom);
      for (int i2 = m; i2 <= i1; i2++) {
            for (int i3 = k; i3 <= n; i3++) {
              if (localBoundingBox.overlap(i3, i2, i3, i2))
              {
                int i4 = pixels[(i2 * width + i3)];
                int i5 = CSAProcessing.blendColor(i4, localDrawable.getColor(i3, i2), j);
                pixels[(i2 * width + i3)] = i5;

              }
          }
        }
      this.totalRender += 1;
    }
  }
}
