package howto;

import java.awt.*;
import java.util.*;

public class OvalShape extends Shape implements Observer
{
   HotSpot _hsT, _hsB,_hsR, _hsL,_hsC;

   int _x, _y, _w, _h;

   public OvalShape(int x, int y, int w, int h)
   {
      _x = x;
      _y = y;
      _w = w;
      _h = h;

      _hsT = new HotSpot(new Coordinates(x + w/2, y));
      _hsB = new HotSpot(new Coordinates(x + w/2, y + h));
      _hsR = new HotSpot(new Coordinates(x + w, y + h/2));
      _hsL = new HotSpot(new Coordinates(x, y + h/2));
      _hsC = new HotSpot(new Coordinates(x + w/2, y + h/2),
                         new Dimensions(11, 11));

      _hsT.addObserver(this);
      _hsB.addObserver(this);
      _hsR.addObserver(this);
      _hsL.addObserver(this);
      _hsC.addObserver(this);
   }

   public Vector getHotSpots()
   {
      Vector vec = new Vector();

      vec.addElement(_hsT);
      vec.addElement(_hsB);
      vec.addElement(_hsR);
      vec.addElement(_hsL);
      vec.addElement(_hsC);

      return vec;
   }

   public void paint(Graphics g)
   {
      int x = _w < 0 ? _x + _w : _x;
      int y = _h < 0 ? _y + _h : _y;
      int w = _w < 0 ? -_w : _w;
      int h = _h < 0 ? -_h : _h;

      g.drawOval(x, y, w, h);
   }

   public void update(Observable obs, Object obj)
   {
      Coordinates coordT = _hsT.getCoordinates();
      Coordinates coordB = _hsB.getCoordinates();
      Coordinates coordR = _hsR.getCoordinates();
      Coordinates coordL = _hsL.getCoordinates();
      Coordinates coordC = _hsC.getCoordinates();

      if (obs == _hsT)
      {
         _y = coordT.y;
         _w = (coordT.x - coordL.x) * 2;
         _h = coordB.y - coordT.y;
      }
      else if (obs == _hsB)
      {
         _w = (coordB.x - coordL.x) * 2;
         _h = coordB.y - coordT.y;
      }
      else if (obs == _hsR)
      {
         _w = coordR.x - coordL.x;
         _h = (coordR.y - coordT.y) * 2;
      }
      else if (obs == _hsL)
      {
         _x = coordL.x;
         _w = coordR.x - coordL.x;
         _h = (coordL.y - coordT.y) * 2;
      }
      else if (obs == _hsC)
      {
         _x = coordC.x - _w/2;
         _y = coordC.y - _h/2;
      }

      _hsT.setCoordinates(new Coordinates(_x + _w/2, _y));
      _hsB.setCoordinates(new Coordinates(_x + _w/2, _y + _h));
      _hsR.setCoordinates(new Coordinates(_x + _w, _y + _h/2));
      _hsL.setCoordinates(new Coordinates(_x, _y + _h/2));
      _hsC.setCoordinates(new Coordinates(_x + _w/2, _y + _h/2));
   }
}
