package howto;

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

public class RectangleShape extends Shape implements Observer
{
   HotSpot _hsTL, _hsTR, _hsBL, _hsBR, _hsC;

   int _x, _y, _w, _h;

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

      _hsTL = new HotSpot(new Coordinates(x, y));
      _hsTR = new HotSpot(new Coordinates(x + w, y));
      _hsBL = new HotSpot(new Coordinates(x, y + h));
      _hsBR = new HotSpot(new Coordinates(x + w, y + h));
      _hsC = new HotSpot(new Coordinates(x + w/2, y + h/2),
                         new Dimensions(11, 11));

      _hsTL.addObserver(this);
      _hsTR.addObserver(this);
      _hsBL.addObserver(this);
      _hsBR.addObserver(this);
      _hsC.addObserver(this);
   }

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

      vec.addElement(_hsTL);
      vec.addElement(_hsTR);
      vec.addElement(_hsBL);
      vec.addElement(_hsBR);
      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.drawRect(x, y, w, h);
   }

   public void update(Observable obs, Object obj)
   {
      Coordinates coordTL = _hsTL.getCoordinates();
      Coordinates coordTR = _hsTR.getCoordinates();
      Coordinates coordBL = _hsBL.getCoordinates();
      Coordinates coordBR = _hsBR.getCoordinates();
      Coordinates coordC = _hsC.getCoordinates();

      if (obs == _hsTL)
      {
         _x = coordTL.x;
         _y = coordTL.y;
         _w = coordBR.x - coordTL.x;
         _h = coordBR.y - coordTL.y;
      }
      else if (obs == _hsTR)
      {
         _y = coordTR.y;
         _w = coordTR.x - coordTL.x;
         _h = coordBR.y - coordTR.y;
      }
      else if (obs == _hsBL)
      {
         _x = coordBL.x;
         _w = coordBR.x - coordBL.x;
         _h = coordBL.y - coordTL.y;
      }
      else if (obs == _hsBR)
      {
         _w = coordBR.x - coordTL.x;
         _h = coordBR.y - coordTL.y;
      }
      else if (obs == _hsC)
      {
         _x = coordC.x - _w/2;
         _y = coordC.y - _h/2;
      }

      _hsTL.setCoordinates(new Coordinates(_x, _y));
      _hsTR.setCoordinates(new Coordinates(_x + _w, _y));
      _hsBL.setCoordinates(new Coordinates(_x, _y + _h));
      _hsBR.setCoordinates(new Coordinates(_x + _w, _y + _h));
      _hsC.setCoordinates(new Coordinates(_x + _w/2, _y + _h/2));
   }
}
