#pragma once
#include "gosGml.hpp"

//===========================================================================//
// File:	 Link.cpp														 //
// Project:  gosGml				                                         //
// Contents:																 //
//---------------------------------------------------------------------------//
// Date      Who    Modification                                             //
// 4/10/00   DP     Created													 //
//---------------------------------------------------------------------------//
// Copyright (C) 2000 Microsoft Corp.						                 //
// All Rights reserved worldwide                                             //
// This unpublished sourcecode is PROPRIETARY and CONFIDENTIAL               //
//===========================================================================//


#include "link.h"

Link::Link(int width, int NumLinks)
	:Width(width),LinkPos(0),MaxLinks(NumLinks)
{
	HitLocs=new LinkBox*[NumLinks];
};

Link::~Link()
{
	Clear();
	delete[] HitLocs;
};

void Link::AddLink(LinkBox link, int height)
{
	gosASSERT(link.Top<link.Bottom && (link.Bottom-link.Top)%height==0);
	if(link.Right<link.Left||link.Top+height!=link.Bottom)
	{ 
		//if it clearly line wraps
		LinkBox* lb = new LinkBox;
		lb->Bottom=link.Top+height;
		lb->Left=link.Left;
		lb->Right=Width;
		lb->Top=link.Top;
		lb->Dest=link.Dest;
		SubAddLink(*lb);
		delete lb;
		LinkBox* r = new LinkBox;
		r->Bottom=link.Bottom;
		r->Left=0;
		r->Right=link.Right;
		r->Top=link.Top+height;
		r->Dest=link.Dest;
		AddLink(*r,height);
		delete r;
	}
	else
	{
		SubAddLink(link);		
	}
};

void Link::SubAddLink(LinkBox link)
{
	if(LinkPos<MaxLinks)
	{
		HitLocs[LinkPos]=new LinkBox;
		HitLocs[LinkPos]->Bottom=link.Bottom;
		HitLocs[LinkPos]->Left=link.Left;
		HitLocs[LinkPos]->Right=link.Right;
		HitLocs[LinkPos]->Top=link.Top;
		HitLocs[LinkPos]->Dest=new char[mstrlen(link.Dest)+1];
		memcpy(HitLocs[LinkPos]->Dest,link.Dest,mstrlen(link.Dest));
		HitLocs[LinkPos]->Dest[mstrlen(link.Dest)]='\0';
		LinkPos++;
	}//else ignore
}

char* Link::TestForHit(XYPair click)
{
	for(int i=0;i<LinkPos;i++)
	{
		if(HitLocs[i]->Left<=click.x&&HitLocs[i]->Right>=click.x&&HitLocs[i]->Bottom>=click.y&&HitLocs[i]->Top<=click.y)
			return HitLocs[i]->Dest;
	}
	return 0;
};

void Link::Clear()
{
	for(int i=0;i<LinkPos;i++)
	{
		delete[] HitLocs[i]->Dest;
		delete HitLocs[i];
	}
	LinkPos=0;
}
