#include "externals.hh"
#include "ui-actions.hh"

#include <imgui_internal.h>


/*= T_KeyboardShortcut =======================================================*/

void T_KeyboardShortcut::toString(
		char* const buffer ,
		const size_t size ) const noexcept
{
	const char ch[ 2 ] = {
		char( ( modifiers & E_KeyboardModifier::SHIFT )
			? toupper( character ) : tolower( character ) ) ,
		0
	};
	snprintf( buffer , size , "%s%s%s" ,
			( modifiers & E_KeyboardModifier::CTRL ) ? "C-" : "" ,
			( modifiers & E_KeyboardModifier::ALT ) ? "A-" : "" ,
			[&]( ) {
				switch ( character ) {
					case ' ': return "<space>";
					case '\n': return "<enter>";
					default: return ch;
				}
			}( ) );
}


/*= T_UIAction ===============================================================*/

void T_UIAction::menuItem( ) const noexcept
{
	const bool e{ enabled ? enabled( ) : true };

	T_String const& title{ text ? text : id };
	const uint32_t ts{ title.size( ) };
	char name[ ts + 1 ];
	memcpy( name , title.data( ) , ts );
	name[ ts ] = 0;

	char kbs[ 20 ];
	char const* kbsp = shortcut ? kbs : nullptr;
	if ( shortcut ) {
		shortcut->toString( kbs , 20 );
	}

	if ( ImGui::MenuItem( name , kbsp , false , e ) ) {
		handler( );
	}
}

void T_UIAction::tbButton( ) const noexcept
{
	using namespace ImGui;
	static T_StringBuilder sb;

	sb.clear( ) << ( icon ? icon : "" ) << "##" << id << '\0';

	const bool e{ enabled ? enabled( ) : true };
	if ( !e ) {
		PushItemFlag( ImGuiItemFlags_Disabled , true );
		PushStyleVar( ImGuiStyleVar_Alpha ,
				GetStyle( ).Alpha * .5f );
	}
	const bool rv{ Button( sb.data( ) , ImVec2{ 20 , 0 } ) };
	if ( e && IsItemHovered( ) ) {
		sb.clear( ) << ( text ? text : id );
		if ( shortcut ) {
			char kbs[ 20 ];
			shortcut->toString( kbs , 20 );
			sb << ' ' << kbs;
		}
		sb << '\0';

		BeginTooltip( );
		Text( "%s" , sb.data( ) );
		EndTooltip( );
	}
	if ( !e ) {
		PopItemFlag( );
		PopStyleVar( );
	}

	if ( rv ) {
		handler( );
	}
}