package adecWatt.model.unit;

import java.awt.geom.Point2D;
import java.util.Collection;
import java.util.Hashtable;

import misc.DimensionDouble;
import misc.ScaledImage;

import adecWatt.model.AdecWatt;
import adecWatt.model.Item;
import adecWatt.model.Prop;

@SuppressWarnings ("serial")
public class Lightplot extends Workspace {

    // ========================================
    public Building		getPattern ()			{ return getBuilding (); }
    public DimensionDouble	getRealSize ()			{ return getBuilding ().getSize (); }
    public ScaledImage		getBlueprint ()			{ return getBuilding ().getBlueprint (); }
    public DimensionDouble	getBlueprintSize ()		{ return getBuilding ().getBlueprintSize (); }
    public Point2D.Double	getBlueprintPos ()		{ return getBuilding ().getBlueprintPos (); }
    public Double		getBlueprintVisibility ()	{ return getBuilding ().getBlueprintVisibility (); }

    public Lightplot (AdecWatt adecWatt, String id) {
	super (adecWatt, id);
    }

    // ========================================
    public void storyChangeBuilding (final Building building) {
	final Building oldBuilding = getBuilding ();
	if (oldBuilding == building)
	    return;
	final Hashtable<Item, Point2D.Double> oldPos = getOutsideItem (building);
	final Hashtable<Item, Point2D.Double> newPos = getMoveInsideItem (building, oldPos);
	story.add (story.new Command (StoryChangeBuilding) {
		public void exec () { moveItem (newPos); changeBuilding (building); }
		public void undo () { changeBuilding (oldBuilding); moveItem (oldPos); }
		public void display () {
		    stateNotifier.broadcastUpdate (BroadcastChangeBuilding);
		    stateNotifier.broadcastDisplay (BroadcastChangePos, oldPos.keySet ().toArray ());
		}
	    });
    }

    // ========================================
    private void changeBuilding (Building building) {
	// XXX localProp ?
	getProp (Prop.PropBuilding).setValue (building.getId ());
    }
    private void moveItem (Hashtable<Item, Point2D.Double> items) {
	for (Item item : items.keySet ())
	    item.changePos (items.get (item));
    }

    // ========================================
    public Hashtable<Item, Point2D.Double> getOutsideItem (Building building) {
	Hashtable<Item, Point2D.Double> result = new Hashtable<Item, Point2D.Double> ();
	DimensionDouble size = building.getRealSize ();
	for (Item item : getInheritedEmbeddedValues ())
	    if (item.isPosOutside (size))
		result.put (item, item.getPos ());
	return result;
    }

    public Hashtable<Item, Point2D.Double> getMoveInsideItem (Building building, Hashtable<Item, Point2D.Double> oldPos) {
	Hashtable<Item, Point2D.Double> result = new Hashtable<Item, Point2D.Double> ();
	DimensionDouble size = building.getRealSize ();
	for (Item item : oldPos.keySet ())
	    result.put (item, Item.getPosInside (size, oldPos.get (item), item.getThetaDegree (), item.getSize ()));
	return result;
    }

    // ========================================
}
