/*  dynmnug.c   */
/*  Copyright 1989 Mountain Math Software  */
/*  All Rights Reserved                    */
#include <string.h>
#include "cgidbg.h"
#include "newaloc.h"
#include "shared.h"
#include "menu.h"
#include "dynmen.h"
#include "remdyn.h"
#include "dynmnu.h"
#include "mkstr.h"


// File for menus that are created dynamically
DynamicMenuServer TheDynamicMenuServer ;

void DynamicMenuServer::AddItem(MenuList * AddToThese, MenuItem * Item)
{
}


void DynamicMenuServer::RemoveItem(MenuList * RemoveFromThese,
	const char * CommandRemove) 
{
}


void DynamicMenuServer::MenuServer(class PacketHeader& Head,const char * Data)
{
	MenuServerCommand Command = (MenuServerCommand) Head.Identifier ;
	int Size = Head.DataSize ;
	// LogOut<<"In DynamicMenuServer::MenuServer, Size = " << Size << "\n" ;
	int EndNodeName = 0;
	for (int i = 0 ; i < Size ; i++) if (!Data[i]) {
		EndNodeName = i ;
		break ;
	}
	const char * ItemName = Data + EndNodeName + 1 ;
	if (!EndNodeName || Data[Size-1]) {
		TheLog << "EndNodeName = " << EndNodeName << "\n" ;
		TheLog << "Data[" << Size -1 << "] = " <<
			(int) Data[Size-1] << "\n" ;
		TheLog << "`" << Data << "'\n" ;
		if (EndNodeName) TheLog << "`" <<
			ItemName << "'\n" ;
		DbgError( "DynamicMenuServer::MenuServer","bad packet data");
	}
/*
 *	 LogOut << "Operating on `" << MenuName << "'  `" << ItemName
 *		<< "'\n" ;
 */
	char * Temp =  0 ;
	if (Command != MenuServerAttachOrphan)
		Data = Temp = Concatenate(Data,"InstancesMenu");
	DoCommand(Command,Data,ItemName);
	delete Temp ;
}

void DynamicMenuServer::DoCommand(MenuServerCommand Command,
	const char * MenuName, const char * ItemName)
{
	DynamicMenuInfo * Info ;
	int EndNodeName = strlen(ItemName);
	if (Command != MenuServerAttachOrphan) {
		for (Info = TheRemoteDynamicMenuTable;
			Info->TheMenu; Info++)
				if (!strcmp(Info->Name,MenuName)) break;
		if (!Info->TheMenu) {
			TheLog << "Looking for `" << MenuName << "'\n" ;
			DbgError("DynamicMenuServer::MenuServer",
				"no such Dynamic menu");
		}
	}

	switch(Command) {
case MenuServerNewMenuItem:
		{
			int NameSize = 1 + strlen(ItemName) ;
			char * NewName = Concatenate(ItemName);
			// LogMsg("NewMenuEntry:",NewName);
			// LogMsg("In Menu:", Info->TheMenu->GetHeader());

			MenuLine * NewLine = new MenuLine ;
			*NewLine = Info->Template ;
			NewLine->Command = NewName ;
			TheDynamicMenuController->AddMenuItem(Info->TheMenu,
				NewLine);
		}
		break ;
case MenuServerDeleteMenuItem:
		{
			int NameSize = 1 + strlen(ItemName) ;
			char * NewName = Concatenate(ItemName);
			// LogMsg("DeleteMenuEntry:",NewName);
			// LogMsg("In Menu:", Info->TheMenu->GetHeader());
			TheDynamicMenuController->DeleteMenuItem(Info->TheMenu,
				NewName);
		}
		break;
case MenuServerAttachOrphan:
		// LogOut << "MenuServerAttachOrphan\n" ;
		AttachOrphan(MenuName, ItemName);
		break ;
	}
}



