#include "NTButton.h"
#include "NTScreen.h"

namespace NTCurses {

void NTButton::InitButton( void ) {
	sValue = "";
	uHeight = 1;
	
	attrActiveEnabled = oCurses->GetAttrFromString( "W+B" );
	attrInactiveEnabled = oCurses->GetAttrFromString( "W-R" );
	attrDisabled = oCurses->GetAttrFromString( "N-W" );
}

NTButton::NTButton( NTWidget *parent ) : NTWidget::NTWidget( parent ) {
	InitButton();
}

NTButton::NTButton( NT::NTString id , NTWidget *parent ) : NTWidget::NTWidget( id , parent ) {
	InitButton();
}

void NTButton::OnClick( void ) {
}


void NTButton::HandleKeyEvent( int keycode ) {
	switch (keycode) {
	case 27:
		if (!oParent) break;
		oParent->PushEvent( NTModalExitEvent( 0 ) );
		break;
	case 9:
	case KEY_RIGHT:
	case KEY_DOWN:
		if (!oParent) break;
		oParent->PushEvent( NTNextNodeControlEvent() );
		SetDirty( true );
		break;
	case KEY_LEFT:
	case KEY_UP:
	case KEY_BTAB:
		if (!oParent) break;
		oParent->PushEvent( NTPrevNodeControlEvent() );
		SetDirty( true );
		break;
	case 10:
		OnClick();
		break;
	}
}

void NTButton::Draw( void ) {
	if (!bDirty) return;

	unsigned int ox,oy;

	ox = GetRelativeX();
	oy = GetRelativeY();

	oCurses->Move( ox , oy );

	unsigned int attr;
	if (bEnabled) {
		attr = (bActive) ? attrActiveEnabled : attrInactiveEnabled;
	} else
		attr = attrDisabled;

	NT::NTString buttonstring = NT::center_pad_string( sValue , uWidth - 4 );
	oCurses->SetAttr( attr );
	oCurses->PutChar( ' ' );
	oCurses->PutChar( ACS_RARROW );
	oCurses->PutString( buttonstring );
	oCurses->PutChar( ACS_LARROW );
	oCurses->PutChar( ' ' );
	if (bActive) {
		NTGetGlobalScreen()->ShowCursor( false );
		NTGetGlobalScreen()->SetCursorState( false );
	}
	bDirty = false;
}

void NTButton::SetValue( NT::NTString s ) {
	if (s==sValue) return;
	sValue = s;
	SetDirty( true );
}

NT::NTString NTButton::GetValue( void ) {
	return sValue;
}

}
