import javax.swing.*;
import java.util.*;

        // Track an individual ship. This receives
        // notifications each time its ship moves.
        // When notified, it should tell its GUI to
        // repaint itself.
class ShipTracker implements Observer {
    public ShipTracker(Ship ship, JComponent gui){
        this.gui = gui;
        setShip(ship);
        // Initialise the position attributes.
        updatePath(ship.getCourseAndPosition());
    }

        // Provide access to the path of the ship via an
        // iterator over its track.
    public Iterator getShipTrack(){
        // Make sure the track is up to date.
        updatePath(ship.getCourseAndPosition());
        return getTrack().iterator();
    }

        // Observer interface - a Ship has moved.
    public void update(Observable o, Object arg){
        updatePath((CourseAndPosition) arg);
        getGui().repaint();
    }

    public void updatePath(CourseAndPosition position){
        CourseAndPosition lastPosition = null;
        LinkedList track = getTrack();
        if(track.size() != 0){
             lastPosition = (CourseAndPosition) track.getLast();
        }
        // Don't add repeated positions.
        if(!position.equals(lastPosition)){
            track.add(position);
        }
    }

    public Ship getShip(){
        return ship;
    }

    public void setShip(Ship s){
        // Stop observing any previous ship.
        if(ship != null){
            ship.deleteObserver(this);
            // Clear the track.
            getTrack().clear();
        }
        ship = s;
        ship.addObserver(this);
    }

    protected JComponent getGui(){
        return gui;
    }

    protected LinkedList getTrack(){
        return track;
    }

    // The Ship being tracked.
    private Ship ship;
    // Where have we been.
    private LinkedList track = new LinkedList();
    // Where the track is drawn.
    private final JComponent gui;
}
