/*	Copyright  (c)	Günter Woigk 2016 - 2016
					mailto:kio@little-bat.de

	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.

	Permission to use, copy, modify, distribute, and sell this software and
	its documentation for any purpose is hereby granted without fee, provided
	that the above copyright notice appear in all copies and that both that
	copyright notice and this permission notice appear in supporting
	documentation, and that the name of the copyright holder not be used
	in advertising or publicity pertaining to distribution of the software
	without specific, written prior permission.  The copyright holder makes no
	representations about the suitability of this software for any purpose.
	It is provided "as is" without express or implied warranty.

	THE COPYRIGHT HOLDER DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE,
	INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO
	EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY SPECIAL, INDIRECT OR
	CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
	DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
	TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
	PERFORMANCE OF THIS SOFTWARE.
*/

#define SAFE 3
#define LOG 1
#include "kio/kio.h"
#include "Object.h"
#include "Templates/Array.h"
#include "Templates/RCArray.h"
#include <QRect>
#include<QPainter>



// All existing objects:
// Object.obj_id is the index in this table.
// first created object (obj_id=0) should be the framebuffer object
Array<Object*>	objects;
Array<ObjID>	free_ObjIds;


//helper:
ObjID Object::newObjId()
{
	if(free_ObjIds.count())
	{
		obj_id = free_ObjIds.pop();
		objects[obj_id] = this;
	}
	else
	{
		obj_id = objects.count();
		objects.append(this);
	}
	return obj_id;
}

void purgeAllObjects()
{
	objects.purge();
	free_ObjIds.purge();
}



// =============================================================
//				Object for GFXPainter
//				implements a tree hierarchy
// =============================================================


Object::Object(IsaID isa_id, const QRect& zbox)
:
	rcnt(0),
	isa_id(isa_id),
	obj_id(newObjId()),
	parent(NULL),
	zbox(zbox)
{}

Object::Object(IsaID isa_id, int x, int y, int w, int h)
:
	rcnt(0),
	isa_id(isa_id),
	obj_id(newObjId()),
	parent(NULL),
	zbox(x,y,w,h)
{}

Object::Object(IsaID isa_id, int w, int h)
:
	rcnt(0),
	isa_id(isa_id),
	obj_id(newObjId()),
	parent(NULL),
	zbox(0,0,w,h)
{}


Object::~Object()
{
	XXASSERT(rcnt==0);

	free_ObjIds.append(obj_id);
}


void Object::dispose()
{
	Object* p = parent;
	objects[obj_id] = nullptr;		// this may already delete this Object!
	if(p) p->removeChild(this);
}


void Object::appendChild(Object* o)
{
	XXASSERT(o->parent == NULL);

	o->parent = this;
	children.append(o);
}


void Object::removeChild(Object* o)
{
	XXASSERT(o->parent == this);

	children.remove(o);
	o->parent = NULL;
}


/*	exchange two objects
	move this object to the position of that object in that object's parent's child list
	and vice versa
	can't be used for root objects (no parent)
*/
void Object::exchange(Object* that)
{
	XXASSERT(this->parent!=NULL);
	XXASSERT(that->parent!=NULL);
	XXASSERT(!that->isDescendantOf(this));
	XXASSERT(!this->isDescendantOf(that));

	// exchange child lists:
	children.swap(that->children);

	for(uint i=0;i<children.count();i++)
		children[i]->parent = this;
	for(uint i=0;i<that->children.count();i++)
		that->children[i]->parent = that;

	// exchange parents:
	Object* tp = this->parent;
	Object* op = that->parent;

	this->parent = op;
	that->parent = tp;

	uint ti = tp->children.indexof(this);
	uint oi = op->children.indexof(that);

	op->children[oi].swap(tp->children[ti]);
}


/*	swap two objects
	swap their object ids too, so that the oids in their parent child lists do not change
	can be used to swap the root objects
	to replace an entire scene or to switch from TTY to GFX or similar.
*/
void Object::swap_all(Object* that)
{
	XXASSERT(!that->isDescendantOf(this));
	XXASSERT(!this->isDescendantOf(that));

	// exchange child lists:
	this->children.swap(that->children);

	// exchange parents:
	Object* tp = this->parent;
	Object* op = that->parent;

	this->parent = op;
	that->parent = tp;

	uint ti = tp?tp->children.indexof(this):0;
	uint oi = op?op->children.indexof(that):0;

	// note: either object may be kept alive by the pointer in parent.children[] only!
	// then overwriting pointer in parent's child list will lead to immediate destruction!

	if(tp && op) op->children[oi].swap(tp->children[ti]);
	else if(op)	 op->children[oi] = this;				// 'that' might self destruct here
	else		 tp->children[ti] = that;				// 'this' might self destruct here

	// exchange obj_ids:
	kio::swap(this->obj_id,that->obj_id);
	kio::swap(objects[this->obj_id],(objects[that->obj_id]));
}


void Object::moveToIndex(int zi)
{
	XXASSERT(parent);

	Objects& p_children = parent->children;
	int qi = p_children.indexof(this);
	XXXASSERT(qi>=0);

	if(zi<qi) p_children.ror(max(0,zi),qi+1); else
	if(qi<zi) p_children.rol(qi,min(zi+1,(int)p_children.count()));
}


void Object::moveToParent(Object* p)
{
	XXASSERT(p != NULL);
	XXASSERT(this->parent != NULL);
	XXASSERT(!p->isDescendantOf(this));

	if(parent==p) return;
	p->children.append(this);		// insert first
	parent->children.remove(this);	// remove then
	parent = p;
}


void Object::replace(Object* old)
{
	XXASSERT(old != NULL);
	XXASSERT(old->parent != NULL);
	XXASSERT(this->parent != NULL);
	XXASSERT(!old->isDescendantOf(this));

	Object* p = old->parent;
	uint i = p->children.indexof(old);
	p->children[i] = this;			// insert first
	parent->children.remove(this);	// remove then
	parent = p;
}


void Object::paint_out(QPainter& p, int dx, int dy)
{
	dx += zbox.left();
	dy += zbox.top();

	for(uint i=0; i < children.count(); i++)
	{
		children[i]->paint_out(p,dx,dy);
	}
}


int Object::paintjob(Stream&, QPainter&) throw(uint)
{
	TODO();
}



// ===========================================================
//				RectObject
// ===========================================================


/*	RectObject creator:
*/
RectObject::RectObject(const QRect& zbox, QRgb color)
:
	Object(IsaRectObject,zbox),
	color(color)
{}

RectObject::RectObject(int x, int y, int w, int h, QRgb color)
:
	Object(IsaRectObject,x,y,w,h),
	color(color)
{}

RectObject::RectObject(int w, int h, QRgb color)
:
	Object(IsaRectObject,w,h),
	color(color)
{}

void RectObject::paint_out(QPainter& p, int dx, int dy)
{
	if(color.alpha() != 0) p.fillRect(zbox.translated(dx,dy),color);
	// else fully transparent
	if(children.count()) Object::paint_out(p,dx,dy);
}

int RectObject::paintjob(Stream&, QPainter&) throw(uint)
{
	TODO();
}

//void RectObject::resetGeometry()
//{
//	TODO();
//}



// ===========================================================
//				GraphicsObject
// ===========================================================


/*	PixmapObject creator:
	maps whole image unscaled to position x,y in parent
*/
GFXObject::GFXObject(GFXPixmap* pixmap, int x, int y)
:
	Object(IsaGFXObject,x,y,pixmap->width(),pixmap->height()),
	pixmap(pixmap),
	qbox(0,0,pixmap->width(),pixmap->height())
{}

GFXObject::GFXObject(int w, int h, QRgb c)
:
	Object(IsaGFXObject,w,h),
	pixmap(new GFXPixmap(w,h,c)),
	qbox(0,0,w,h)
{}

void GFXObject::paint_out(QPainter& p, int dx, int dy)
{
	p.drawPixmap(zbox.translated(dx,dy), pixmap, qbox);
	if(children.count()) Object::paint_out(p,dx,dy);
}

int GFXObject::paintjob(Stream&, QPainter&) throw(uint)
{
	TODO();
}

void GFXObject::resetGeometry()
{
	TODO();
}

void GFXObject::setQPos(int x, int y)
{
	TODO();
}

void GFXObject::setQSize(uint w, uint h)
{
	TODO();
}




// ===========================================================
//				Vector Graphics Object
// ===========================================================

CRTObject::CRTObject(const QRect& zbox, QRgb color)
:
	Object(IsaCRTObject,zbox),
	color(color)
{}

CRTObject::CRTObject(int x, int y, int w, int h, QRgb color)
:
	Object(IsaCRTObject,x,y,w,h),
	color(color)
{}

CRTObject::CRTObject(int w, int h, QRgb color)
:
	Object(IsaCRTObject,w,h),
	color(color)
{}

void CRTObject::paint_out(QPainter& p, int dx, int dy)
{
	p.setPen(color);

	int l = dx + zbox.left();
	int r = dx + zbox.right();
	int o = dy + zbox.top();
	int u = dy + zbox.bottom();
	int m = (l+r)/2;
	int c = (o+u)/2;

	QPolygon vertices = QVector<QPoint>()
		<< QPoint(l,c)
		<< QPoint(m,o)
		<< QPoint(r,c)
		<< QPoint(m,u)
		<< QPoint(l,c);
	p.drawPolyline(vertices);

	if(children.count()) Object::paint_out(p,dx,dy);
}

int CRTObject::paintjob(Stream&, QPainter&) throw(uint)
{
	TODO();
}


void CRTObject::resetGeometry()
{
	TODO();
}

void CRTObject::setQSize(uint w, uint h)
{
	TODO();
}































