/******************************************************************************
 *    FixupPlayerLinks.cpp
 *
 *    This file is part of Object Script Library
 *    Copyright (C) 2005-2009 Tom N Harris <telliamed@whoopdedo.org>
 *
 *    Permission is hereby granted, free of charge, to any person obtaining
 *    a copy of this software and associated documentation files (the 
 *    "Software"), to deal in the Software without restriction, including 
 *    without limitation the rights to use, copy, modify, merge, publish, 
 *    distribute, sublicense, and/or sell copies of the Software, and to 
 *    permit persons to whom the Software is furnished to do so.
 *    
 *    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
 *    EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
 *    OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-
 *    INFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS 
 *    BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN 
 *    AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 
 *    IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 
 *    THE SOFTWARE.
 *
 *****************************************************************************/

#include "ScriptLib.h"

static int FixupPlayerLinksFunc(ILinkSrv*, ILinkQuery* pLQ, IScript*, void* pData)
{
	// Move the destination of the link to the object specified in pData
	SInterface<ILinkManager> pLM(g_pScriptManager);
	int iPlayer = reinterpret_cast<int>(pData);
	sLink slInfo;
	pLQ->Link(&slInfo);
	long lNew = pLM->Add(slInfo.source, iPlayer, slInfo.flavor);
	if (lNew)
	{
		void* pLinkData = pLQ->Data();
		if (pLinkData)
			pLM->SetData(lNew, pLinkData);
	}
	pLM->Remove(pLQ->ID());
	return 1;
}

void FixupPlayerLinks(int iSource, int iPlayer)
{
	SService<ILinkSrv> pLS(g_pScriptManager);
	SService<ILinkToolsSrv> pLTS(g_pScriptManager);
	// Get the PlayerFactory link. There should only ever be one of these.
	link lPFLink;
	pLS->GetOne(lPFLink, pLTS->LinkKindNamed("PlayerFactory"), 0, 0);
	if (lPFLink == 0)
		return;
	// Iterate through all links from here to the source of the PF link.
	sLink lPFInfo;
	pLTS->LinkGet(lPFLink, lPFInfo);
	IterateLinks(NULL, iSource, lPFInfo.source, FixupPlayerLinksFunc, NULL, reinterpret_cast<void*>(iPlayer));
}
