/*  Motti -- a strategy game
    Copyright (C) 1999 Free Software Foundation

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include <X11/Xlib.h>
#include <X11/Xutil.h>

#include "xwin.h"
#include "map.h"
#include "occupy.h"

extern Window main_win;
extern Window but_win[NBUTS];
extern Window map_win;
extern Cursor active_cursor, disabled_cursor;

extern Display *display;
extern int screen_num;

extern void
event_loop ()
{
  char last_modes, last_attacks;
  last_modes = 0;
  last_attacks = game_map.n_att;

  XSelectInput (display, main_win, 0);
  XSelectInput (display, but_win[ATT], ButtonPressMask);
  XSelectInput (display, but_win[DEF], ButtonPressMask);
  XSelectInput (display, but_win[GUE], ButtonPressMask);
  XSelectInput (display, map_win, ExposureMask | ButtonPressMask);

  XMapWindow (display, map_win);
  XMapWindow (display, but_win[ATT]);
  XMapWindow (display, but_win[DEF]);
  XMapWindow (display, but_win[GUE]);
  XMapWindow (display, main_win);
  update_buttons (&last_modes, &last_attacks);

  while (1)
    {
      XEvent report;
      XNextEvent (display, &report);

      switch (report.type)
	{
	  Action map_events;

	case Expose:
	  draw_map (report.xexpose.x, report.xexpose.y,
		    report.xexpose.width, report.xexpose.height);
	  break;

	case ButtonPress:
	  if (!report.xbutton.same_screen) break;
	  if (report.xbutton.window == but_win[ATT])
	    {
	      action (MODE_ATT, &map_events);
	      draw_effects (map_events);
	    }
	  else if (report.xbutton.window == but_win[DEF])
	    {
	      action (MODE_DEF, &map_events);
	      draw_effects (map_events);
	    }
	  else if (report.xbutton.window == but_win[GUE])
	    {
	      action (MODE_GUE, &map_events);
	      draw_effects (map_events);
	    }
	  else if (report.xbutton.window == map_win)
	    {
	      Coord coord;
	      coord = win_pos2map_coord (report.xbutton.x,
					 report.xbutton.y);

	      if (toggle_cross (coord))
		draw_map (report.xbutton.x, report.xbutton.y, 0, 0);
	    }
	  update_buttons (&last_modes, &last_attacks);
	  break;
	}
    }
}
