/*
 * @(#)BufferedUpdateStrategy.java 5.1
 *
 */

package CH.ifa.draw.standard;

import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Image;
import java.io.Serial;

import de.renew.draw.ui.ontology.DrawingView;
import de.renew.draw.ui.ontology.Painter;


/**
 * The BufferedUpdateStrategy implements an update
 * strategy that first draws a view into a buffer
 * followed by copying the buffer to the DrawingView.
 * @see DrawingView
 */
public class BufferedUpdateStrategy implements Painter {
    /*
     * Serialization support.
     */
    @Serial
    private static final long serialVersionUID = 6489532222954612824L;
    private final int _bufferedUpdateSerializedDataVersion = 1;

    /**
    * The offscreen image
    */
    transient private Image _offscreen;
    private int _imageWidth = -1;
    private int _imageHeight = -1;

    /**
     * Draws the view contents.
     */
    public void draw(Graphics g, DrawingView view) {
        // create the buffer if necessary
        Dimension d = view.getSize();
        if ((_offscreen == null) || (d.width != _imageWidth) || (d.height != _imageHeight)) {
            _offscreen = view.createImage(d.width, d.height);
            _imageWidth = d.width;
            _imageHeight = d.height;
        }

        // let the view draw on offscreen buffer
        Graphics g2 = _offscreen.getGraphics();

        view.drawAll(g2);

        g.drawImage(_offscreen, 0, 0, view);
    }
}