// BOSSTUI.CPP
//
// Copyright (c) 1998 Symbian Ltd.  All rights reserved.
//

#include "bosseng.h"
#include "tuiedit.h"

/*
	class CBossTextUi - defines text UI
*/

class CBossTextUi : public CBase
	{
public:
	// execute UI until exit command processed
	void ExecuteL();
private:
	// destructor
	~CBossTextUi();
	// other functions
	void Draw();
	void DoCommandL();
private:
	TBossPuzzle iPuzzle;
	CConsoleBase* iConsole;
	CLineEdit* iCommandLine;
	TBuf<80> iCommand;
	};

/*
	ok, real stuff starts here
*/

void CBossTextUi::ExecuteL()
	{
	//constant declarations
	_LIT(KBossPuzzleTextUI,"Boss Puzzle Text UI");
	_LIT(KPrompt,">");

	iConsole=Console::NewL(KBossPuzzleTextUI,
		TSize(KDefaultConsWidth,KDefaultConsHeight));
	iCommandLine=CLineEdit::NewL(iConsole,10);
	iPuzzle.SetFullyOrdered();
	for (;;)
		{		
		iCommandLine->Edit(KPrompt, &iCommand);
		DoCommandL();
		}
	}

CBossTextUi::~CBossTextUi()
	{
	delete iCommandLine;
	delete iConsole;
	}

void CBossTextUi::Draw()
	{
	//constant declarations
	_LIT(KAppendFormat,"%2d");  
	_LIT(KBlankZapper,"--");
	_LIT(KRowFormat,"%S\n");
	/* note: such short strings are very inefficient at function scope
					 - should declare at file scope */
	
	// start by formatting the rows with tile number, or 00 for blank
	TBuf<11> rows[4];
	TInt row;
	for (row=0; row<4; row++)
		{
		rows[row].Zero();
		for (TInt col=0; col<4; col++)
			{
			if (col>0) rows[row].Append(' ');
			rows[row].AppendFormat(KAppendFormat, (TInt) iPuzzle.Tile(row,col));
			}
		}
	// find blank position, and replace number with symbol
	TInt blankRow, blankCol;
	iPuzzle.LocateBlank(blankRow, blankCol);
	TPtr blankZapper((TText*)(rows[blankRow].Ptr())+3*blankCol, 2);
	blankZapper=KBlankZapper;
	// write out the strings to the console
	for (row=0; row<4; row++)
		iConsole->Printf(KRowFormat, &(rows[row]));
	}

void CBossTextUi::DoCommandL()
	{
	_LIT(KUnknownCmnd,"unknown command\n"); //constant declaration
	
	if (iCommand.Length()==0); // nothing
	else if (iCommand[0]=='q') User::Leave(KErrNone);
	else if (iCommand[0]=='v') Draw();
	else
		{
		iConsole->Printf(KUnknownCmnd);
		}
	}

/*
	harness
*/

LOCAL_C void executeUiL()
	{
	CBossTextUi* textUi=new (ELeave) CBossTextUi;
	CleanupStack::PushL(textUi);
	textUi->ExecuteL();
	CleanupStack::PopAndDestroy();
	}

GLDEF_C TInt E32Main() // main function called by E32
    {
	__UHEAP_MARK; // mark heap state
	_LIT(KBossPuzzlePanic,"BossPuzzle"); //constant declaration
	CTrapCleanup* cleanup=CTrapCleanup::New(); // get clean-up stack
	TRAPD(error,executeUiL()); // do most stuff under cleanup stack
	__ASSERT_ALWAYS(!error,User::Panic(KBossPuzzlePanic,error));
	delete cleanup; // destroy clean-up stack
	__UHEAP_MARKEND; // check no memory leak
	return 0; // and return
    }

