#include <GL/gl.h>
#include "rotzoom.h"
#include "matrix.h"

void RotZoomer::SetGLViewMatrix (void) const
{
  glMatrixMode(GL_MODELVIEW);
  glLoadIdentity ();

  glTranslatef (0, 0, -_dist);
  
  Matrix rotm;
  _tb.BuildRotationMatrix (rotm);
  glMultMatrixf ((float *)rotm);
  glTranslatef (-_focus_pt.x(), -_focus_pt.y(), -_focus_pt.z());

  Vec4 z (0,0,-_dist);
  JLmatrix jm;
  _tb.BuildRotationMatrix (jm);
  z *= jm;

#if 0
  z *= .5;
  //  cerr << "z is now " << z << endl;
  z+=_focus_pt;
  z = _focus_pt;

  glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
  glColor3f (1,1,1);
  glBegin (GL_QUADS);
  glVertex3fv ((z+Vec4(10,10,0)).ArrayForGL());
  glVertex3fv ((z+Vec4(10,-10,0)).ArrayForGL());
  glVertex3fv ((z+Vec4(-10,-10,0)).ArrayForGL());
  glVertex3fv ((z+Vec4(-10,10,0)).ArrayForGL());
  glEnd ();
#endif

}

void RotZoomer::move (XEvent *ev)
{
  float x, y;
  _mouse.Update(ev->xmotion.x, ev->xmotion.y);
  _mouse.GetFloatXYGivenViewport(x, y, _w, _h);

  if (_mouse.IsMouseDown (0))
    _tb.Drag (x, -y);

  if (_mouse.IsMouseDown (1))
    cerr << "dont' know how to pan yet." << endl;

  if (_mouse.IsMouseDown (2))
    {
      int diffy = _mouse.last_y() - _mouse.y();

      _dist += diffy*_zoom_speed;
    }

  //  cerr << "dragged to " << ev->xmotion.x << ", " << ev->xmotion.y << endl;
  
}

void RotZoomer::btnDown (XEvent *ev)
{
  float x, y;

  int button = ev->xbutton.button - 1;

  _mouse.MouseDown(button);
  _mouse.Update(ev->xbutton.x, ev->xbutton.y);
        
  switch (button)
    {
    case 0: // rotate
      _mouse.GetFloatXYGivenViewport(x, y, _w, _h);
      _tb.Click (x, -y);
      break;
    case 1: // pan
      break;
    case 2: // zoom
      break;
    }

  //  cerr << "clicked button " << button << " at " << ev->xbutton.x << ", " << ev->xbutton.y << endl;
}


void RotZoomer::btnUp (XEvent *ev)
{
  int button = ev->xbutton.button - 1;
  //  cerr << "up event for button " << button << endl;
  if (_mouse.IsMouseDown(button))
    {
      _mouse.MouseUp(button);
    }
}

