/** 
 *  Yudit Unicode Editor Source File
 *
 *  GNU Copyright (C) 1997-2006  Gaspar Sinai <gaspar@yudit.org>  
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License, version 2,
 *  dated June 1991. See file COPYYING for details.
 *
 *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
 
#include "swindow/SRedrawEvent.h"
#include <stdio.h>
/**
 * Redraw event that can be put in a hashtable.
 * It is very efficient to collapse many SRedrawEvent object with merge.
 */

SRedrawEvent::SRedrawEvent (bool _clear, int _x, int _y, 
  unsigned int _width, unsigned int _height)
{
  clear = _clear;
  x = _x;
  y = _y;
  width = _width;
  height = _height;
}

SRedrawEvent::SRedrawEvent (const SRedrawEvent& evt)
{
  clear = evt.clear;
  x = evt.x;
  y = evt.y;
  width = evt.width;
  height = evt.height;
}

SRedrawEvent::~SRedrawEvent()
{
}

SRedrawEvent
SRedrawEvent::operator=(const SRedrawEvent& evt)
{
  clear = evt.clear;
  x = evt.x;
  y = evt.y;
  width = evt.width;
  height = evt.height;
  return *this;
}

SObject*
SRedrawEvent::clone () const
{
  return new SRedrawEvent (*this);
}


/**
 * Merge this event with another one.
 * return false if they can not be merged because they
 * don't overlap.
 */
bool
SRedrawEvent::merge (const SRedrawEvent& evt)
{
/*/
  unsigned int mew = width;
  unsigned int meh = height;
  unsigned int youw = evt.width;
  unsigned int youh = evt.height;
*/
  /* check if they have overlapping areas */
  /* maximum start */
  int maxx = (x > evt.x) ? x : evt.x;
  int maxy = (y > evt.y) ? y : evt.y;

  /* minimum end */
  int minx = (x+(int) width < evt.x + (int) evt.width) 
         ? x+(int) width : evt.x + (int) evt.width;

  int miny = (y+(int) height < evt.y + (int) evt.height) 
         ? y+(int) height : evt.y + (int) evt.height;

  if (maxx > minx || maxy > miny) return false; 

  if (evt.clear) clear = true;
  int oldx1 = x + (int) width;
  int oldy1 = y + (int) height;
  int newx1 = evt.x + (int) evt.width;
  int newy1 = evt.y + (int) evt.height;

  if (evt.x < x) x = evt.x;
  if (evt.y < y) y = evt.y;
  if (newx1 > oldx1) oldx1 = newx1;
  if (newy1 > oldy1) oldy1 = newy1;
  width = (unsigned int) (oldx1 - x);
  height = (unsigned int) (oldy1 - y);
/*
  if (width == 10 && height == 200) {
     fprintf (stderr, "merge 10,200\n");
  }
  if (width == 20 && height == 341) {
     fprintf (stderr, "merge 20,341 me=%u,%u you=%u,%u\n", 
         mew, meh, youw, youh);
  }
*/
  /* mergeable */
  return true;
}
