/**
 * \file Action.cpp
 * This file is part of LyX, the document processor.
 * Licence details can be found in the file COPYING.
 *
 * \author Abdelrazak Younes
 *
 * Full author contact details are available in file CREDITS.
 */

#include <config.h>

#include "Action.h"
#include "GuiApplication.h"

// DispatchResult.h is needed by the windows compiler because lyx::dispatch
// returns a DispatchResult const reference. Gcc does not complain. Weird...
#include "FuncRequest.h"
#include "FuncStatus.h"
#include "LyX.h"

#include "support/debug.h"

using namespace std;


namespace lyx {
namespace frontend {


Action::Action(FuncRequest func, QIcon const & ltr_icon, QString const & text,
               QString const & tooltip, QObject * parent,
               QIcon const & rtl_icon)
	: Action(make_shared<FuncRequest>(std::move(func)), ltr_icon, text, tooltip,
	         parent, rtl_icon)
{}


Action::Action(shared_ptr<FuncRequest const> const & func,
               QIcon const & ltr_icon, QString const & text,
               QString const & tooltip, QObject * parent,
               QIcon const & rtl_icon)
	: QAction(parent), func_(func), ltr_icon_(ltr_icon),
	  rtl_icon_(rtl_icon), is_rtl_(false)
{
	init(text, tooltip);
}


void Action::init(QString const & text, QString const & tooltip)
{
	// only Qt/Mac handles that
	setMenuRole(NoRole);
	setText(text);
	setToolTip(tooltip);
	setStatusTip(tooltip);
	setIcon(ltr_icon_);
	connect(this, SIGNAL(triggered()), this, SLOT(action()));
	update();
}


void Action::update()
{
	FuncStatus const status = getStatus(*func_);

	if (status.onOff(true)) {
		setCheckable(true);
		setChecked(true);
	} else if (status.onOff(false)) {
		setCheckable(true);
		setChecked(false);
	} else {
		setCheckable(false);
	}

	if (!rtl_icon_.isNull()) {
		bool become_rtl = guiApp->rtlContext();
		/* setIcon always triggers an ActionChanged event, regardless of whether
		   it actually changes, so we need to call it only if needed (#13324) */
		if (is_rtl_ != become_rtl) {
			setIcon(become_rtl ? rtl_icon_ : ltr_icon_);
			is_rtl_ = become_rtl;
		}
	}

	setEnabled(status.enabled());
}


void Action::action()
{
	//LYXERR(Debug::ACTION, "calling lyx::dispatch: func_: ");

	lyx::dispatch(*func_);
	triggered(this);
}

} // namespace frontend
} // namespace lyx

#include "moc_Action.cpp"
