package de.renew.gui;

import java.awt.Dimension;
import java.rmi.RemoteException;
import java.util.Hashtable;

import CH.ifa.draw.standard.StandardDrawing;
import de.renew.remote.PlaceInstanceAccessor;


public class TokenBagDrawing extends StandardDrawing {
    private static final Hashtable<PlaceInstanceAccessor, TokenBagDrawing> drawingsByInstance =
        new Hashtable<>();

    /**
     * The place instance whose contents should be displayed
     * in this drawing.
     * @serial
     **/
    private PlaceInstanceAccessor placeInstance;

    /**
     * The figure which is used to display the contents of
     * the place instance.
     * @serial
     **/
    private TokenBagFigure tokenBag;

    private TokenBagDrawing(PlaceInstanceAccessor pi) {
        this.placeInstance = pi;
        drawingsByInstance.put(pi, this);

        String name;
        try {
            name = placeInstance.asString();
        } catch (RemoteException e) {
            // Show the user the problem
            name = e.toString();
        }
        setName(name);

        tokenBag = new TokenBagFigure(this, null, pi, PlaceFigure.EXPANDED_TOKENS);
        add(tokenBag);
    }

    static TokenBagDrawing getTokenBagDrawing(PlaceInstanceAccessor pi) {
        // forbid concurrent searches for instance drawings.
        synchronized (drawingsByInstance) {
            // find instance drawing:
            if (drawingsByInstance.containsKey(pi)) {
                return drawingsByInstance.get(pi);
            } else {
                return new TokenBagDrawing(pi);
            }
        }
    }

    @Override
    public void release() {
        if (placeInstance != null) {
            drawingsByInstance.remove(placeInstance);
            placeInstance = null;
            tokenBag = null;
        }
        super.release();
    }

    @Override
    public void setAttribute(String name, Object value) {
        tokenBag.setAttribute(name, value);
    }

    /**
     * Returns whether drawing has been modified since last save.
     */
    @Override
    public boolean isModified() {
        return false; // a TokenBagDrawing should not be saved!
    }

    @Override
    public Dimension defaultSize() {
        return new Dimension(100, 50);
    }

    @Override
    public String getWindowCategory() {
        return "Token bags";
    }
}