package util;

import java.awt.*;
import java.awt.image.*;
import java.awt.geom.*;
import java.io.*;
import DrawTop.*;
import shape.*;

public class ScreenImage implements Serializable, Cloneable{

    ShapeContainer[] containers;
    Rectangle2D imageArea;
    BufferedImage bufferedImage;
	int debug=1;
    
    public ScreenImage(ShapeContainer[] containers){
        double scale=DrawParameters.getScale();
        this.containers=containers;
        this.imageArea=this.getImageSize(scale, 10, 10);
        int width=(int)imageArea.getWidth();
        int height=(int)imageArea.getHeight();
        this.bufferedImage=new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
        Graphics2D g2 = this.bufferedImage.createGraphics();
        this.drawImage(g2, scale);
    }
    
    private Rectangle2D getImageSize(double scale,int marginX, int marginY){

        Rectangle2D box=ShapeElementUtil.getBoundingBox(this.containers);
        double x0=scale*box.getX();
        double y0=scale*box.getY();
        double width =scale*box.getWidth();
        double height=scale*box.getHeight();
        Rectangle2D area=new Rectangle2D.Double(x0-marginX, y0-marginY,
                    width+2*marginX, height+2*marginY);

        return area;
    }

    private void drawImage(Graphics g, double scale) {
        DrawParameters.DrawMode=DrawParameters.DrawOnImage;
        Graphics2D g2=(Graphics2D)g;
        Color currentColor=g2.getColor();
		if(debug>0) System.out.println("** drawImage currentColor="+currentColor);
        g2.translate(-this.imageArea.getX(), -this.imageArea.getY());
        g2.setColor(Color.WHITE);
        g2.fill(this.imageArea);
        g2.setColor(currentColor);
		g2.setColor(Color.BLACK);
        g2.scale(scale, scale);
        for(int i=0;i<this.containers.length;i++){
            this.containers[i].drawShape(g2);
        }
        g2.scale(1d/scale, 1d/scale);
        g2.translate(this.imageArea.getX(), this.imageArea.getY());
        g2.setColor(currentColor);
        g2.scale(1d, 1d);
        DrawParameters.DrawMode=DrawParameters.DrawOnScreen;
    }

    public Image getImage(){
        return this.bufferedImage;
    }

    public String toString(){
        String str="";
        str+="image area on DrawPanel x,y="+(int)imageArea.getX()+","+(int)imageArea.getY();
        str+="  w, h="+(int)imageArea.getWidth()+","+(int)imageArea.getHeight();
        for(int i=0;i<containers.length;i++) str+="\n  -- "+containers[i].toString();
        return str;
    }
}
