#ifndef _C4D_BASELINK_ARRAY_H_
#define _C4D_BASELINK_ARRAY_H_

#ifdef __API_INTERN__
	#include "c4d_alias.h"
#endif

#include "ge_autoptr.h"
#include "c4d_misc.h"

class BaseLinkArray : public c4d_misc::BaseArray<BaseLink*>
{
	public:
		~BaseLinkArray()
		{
			FlushAll();
		}

		void FlushAll()
		{
			BaseLink *c; LONG i;

			for (i = 0; i < GetCount(); ++i)
			{
				c = (*this)[i]; if (!c) continue;
				BaseLink::Free(c);
			}
			Reset();
		}

		LONG Find(C4DAtomGoal *bl,BaseDocument *doc) const
		{
			LONG i;
			for (i=0;i<GetCount();i++)
			{
				BaseLink *l = (*this)[i]; if (!l) continue;
				C4DAtomGoal *b = l->GetLink(doc); if (!b) continue;
				if (b==bl)
					return i;
			}
			return NOTOK;
		}

		BaseLink *GetIndexLink(LONG i) const
		{
			if (i < 0 || i >= GetCount())
				return NULL; 

			return (*this)[i];
		}

		C4DAtomGoal *GetIndex(LONG i,BaseDocument *doc) const
		{
			if (i < 0 || i >= GetCount())
				return NULL; 

			BaseLink *l = (*this)[i]; if (!l) return NULL;
			return l->GetLinkAtom(doc);
		}

		BaseList2D *GetIndexBl(LONG i,BaseDocument *doc,LONG instanceof=Tbaselist2d) const
		{
			if (i < 0 || i >= GetCount())
				return NULL; 

			BaseLink *l = (*this)[i]; if (!l) return NULL;
			return (BaseList2D*)l->GetLinkAtom(doc,instanceof);
		}

		Bool Remove(LONG n)
		{
			if (n < 0 || n >= GetCount())
				return FALSE;

			BaseLink *l = (*this)[n];
			if (l) BaseLink::Free(l);

			Erase(n); 
			
			return TRUE;
		}

		Bool Append(C4DAtomGoal *bl)
		{
			BaseLink *l = BaseLink::Alloc(); if (!l) return FALSE;
			l->SetLink(bl);
			return c4d_misc::BaseArray<BaseLink*>::Append(l) != NULL;
		}

		LONG GetRealCount(BaseDocument *doc) const
		{
			LONG realcnt=0;
			LONG i,cnt = GetCount();
			for (i=0;i<cnt;i++)
			{
				C4DAtomGoal *bl = GetIndex(i,doc);
				if (bl) realcnt++;
			}
			return realcnt;
		}

		void GetAtomArray(BaseDocument *doc, AtomArray &res) const
		{
			LONG i,cnt = GetCount();
			for (i=0;i<cnt;i++)
			{
				C4DAtomGoal *bl = GetIndex(i,doc);
				if (bl) res.Append(bl);
			}
		}

		void FromAtomArray(const AtomArray &ar)
		{
			FlushAll();
			LONG i,cnt = ar.GetCount();
			for (i=0;i<cnt;i++)
			{
				Append((C4DAtomGoal*)ar.GetIndex(i));
			}
		}
};

#endif
