#include "virtual_keyboard_layout.h"

#include <QJsonArray>
#include <QJsonObject>


VirtualKeyboardLayout::VirtualKeyboardLayout(QJsonObject root) {
	default_page = root["default_page"].toString();
	auto pa      = root["pages"].toArray();
	for (auto p: pa) {
		auto page = new VirtualKeyboardLayoutPage(p.toObject());
		if (page->isValid()) {
			connect(page, &VirtualKeyboardLayoutPage::gotoPageRequest, this, &VirtualKeyboardLayout::gotoPageRequest);
			connect(page, &VirtualKeyboardLayoutPage::hideRequest, this, &VirtualKeyboardLayout::hideRequest);
			pages << page;
		} else
			delete page;
	}
}


VirtualKeyboardLayout::~VirtualKeyboardLayout() {
	// piDeleteAllAndClear(pages);
}


VirtualKeyboardLayoutPage * VirtualKeyboardLayout::getPageByName(QString name) const {
	for (auto p: pages)
		if (p->name() == name) return p;
	return nullptr;
}


void VirtualKeyboardLayout::setDefaultPage() {
	emit gotoPageRequest(default_page);
}


void VirtualKeyboardLayout::setCurrentPage(VirtualKeyboardLayoutPage * p) {
	current_page = p;
}


void VirtualKeyboardLayout::applyHints(Qt::InputMethodHints hints) {
	// qDebug() << hints << current_page;
	if (hints.testFlag(Qt::ImhPreferNumbers) || hints.testFlag(Qt::ImhDigitsOnly)) gotoPageRequest("numeric");
	if (hints.testFlag(Qt::ImhPreferLatin) || hints.testFlag(Qt::ImhLatinOnly)) gotoPageRequest("latin");
	if (hints.testFlag(Qt::ImhPreferLowercase) || hints.testFlag(Qt::ImhLowercaseOnly) || hints.testFlag(Qt::ImhNoAutoUppercase))
		setCapital(false);
	else
		setCapital(true);
	setGotoEnabled(!hints.testFlag(Qt::ImhDigitsOnly) && !hints.testFlag(Qt::ImhLatinOnly));
	setCapitalEnabled(!hints.testFlag(Qt::ImhUppercaseOnly) && !hints.testFlag(Qt::ImhLowercaseOnly));
}


void VirtualKeyboardLayout::setGotoEnabled(bool yes) {
	for (auto p: pages)
		p->setGotoEnabled(yes);
}


void VirtualKeyboardLayout::setCapitalEnabled(bool yes) {
	for (auto p: pages)
		p->setCapitalEnabled(yes);
}


void VirtualKeyboardLayout::setCapital(bool yes) {
	for (auto p: pages)
		p->setCapital(yes);
}
