/*
 * Copyright (C) 2014-2022 CZ.NIC
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 * In addition, as a special exception, the copyright holders give
 * permission to link the code of portions of this program with the
 * OpenSSL library under certain conditions as described in each
 * individual source file, and distribute linked combinations including
 * the two.
 */

#include <QColorDialog>

#include "src/datovka_shared/graphics/colour.h"
#include "src/gui/dlg_msg_box_informative.h"
#include "src/gui/dlg_tag.h"
#include "src/io/tag_db.h"
#include "src/io/tag_client.h"
#include "src/io/tag_container.h"
#include "ui_dlg_tag.h"

DlgTag::DlgTag(const TagItem &tag, QObject *tagStorage, QWidget *parent)
    : QDialog(parent),
    m_ui(new (::std::nothrow) Ui::DlgTag),
    m_tagStorage(tagStorage),
    m_originalTagItem(tag),
    m_modifiedTagItem(tag),
    m_canSaveData(false)
{
	m_ui->setupUi(this);
	/* Tab order is defined in UI file. */

	m_ui->currentColor->setEnabled(false);
	m_ui->tagNamelineEdit->setText(m_modifiedTagItem.name());
	tagNameChanged(m_modifiedTagItem.name());
	setPreviewButtonColor(m_modifiedTagItem);

	connect(m_ui->tagNamelineEdit, SIGNAL(textChanged(QString)),
	    this, SLOT(tagNameChanged(QString)));
	connect(m_ui->changeColorPushButton, SIGNAL(clicked()),
	    this, SLOT(chooseNewColor()));
}

DlgTag::~DlgTag(void)
{
	delete m_ui;
}

bool DlgTag::createTag(TagContainer *tagCont, QWidget *parent)
{
	if (Q_UNLIKELY(Q_NULLPTR == tagCont)) {
		Q_ASSERT(0);
		return false;
	}

	DlgTag dlg(TagItem(), tagCont, parent);
	/* No need to watch content changes when creating new entry. */
	dlg.m_canSaveData = tagCont->isResponding();
	if (dlg.exec() == QDialog::Accepted) {
		return saveTag(tagCont, dlg.m_modifiedTagItem, parent);
	}
	return false;
}

bool DlgTag::editTag(TagContainer *tagCont, const TagItem &tag, QWidget *parent)
{
	if (Q_UNLIKELY(Q_NULLPTR == tagCont)) {
		Q_ASSERT(0);
		return false;
	}

	DlgTag dlg(tag, tagCont, parent);
	dlg.databaseConnectActions(tagCont); /* Watch content changes. */
	dlg.m_canSaveData = tagCont->isResponding();
	if (dlg.exec() == QDialog::Accepted) {
		return saveTag(tagCont, dlg.m_modifiedTagItem, parent);
	}
	return false;
}

bool DlgTag::editTag(TagDb *tagDb, const TagItem &tag, QWidget *parent)
{
	if (Q_UNLIKELY(Q_NULLPTR == tagDb)) {
		Q_ASSERT(0);
		return false;
	}

	DlgTag dlg(tag, tagDb, parent);
	dlg.databaseConnectActions(tagDb); /* Watch content changes. */
	dlg.m_canSaveData = true;
	if (dlg.exec() == QDialog::Accepted) {
		return saveTag(tagDb, dlg.m_modifiedTagItem, parent);
	}
	return false;
}

bool DlgTag::editTag(TagClient *tagClient, const TagItem &tag, QWidget *parent)
{
	if (Q_UNLIKELY(Q_NULLPTR == tagClient)) {
		Q_ASSERT(0);
		return false;
	}

	DlgTag dlg(tag, tagClient, parent);
	dlg.databaseConnectActions(tagClient); /* Watch content changes. */
	dlg.m_canSaveData = tagClient->isConnected();
	if (dlg.exec() == QDialog::Accepted) {
		return saveTag(tagClient, dlg.m_modifiedTagItem, parent);
	}
	return false;
}

void DlgTag::tagNameChanged(const QString &tagName)
{
	m_modifiedTagItem.setName(tagName);

	enableOkButton();
}

void DlgTag::chooseNewColor(void)
{
	QColor colour = QColorDialog::getColor(QColor("#" + m_modifiedTagItem.colour()),
	    this, tr("Choose tag colour"));

	if (colour.isValid()) {
		QString colourName = colour.name().toLower().replace("#", "");
		if (Colour::isValidColourStr(colourName)) {
			m_modifiedTagItem.setColour(colourName);
		}
		setPreviewButtonColor(m_modifiedTagItem);
		enableOkButton();
	}
}

void DlgTag::watchTagsUpdated(const Json::TagEntryList &entries)
{
	for (const Json::TagEntry &entry : entries) {
		if (Q_UNLIKELY(!entry.isValid())) {
			continue;
		}
		if (m_modifiedTagItem.id() != entry.id()) {
			continue;
		}

		/* Update dialogue content if the content has not been changed already. */
		if (m_originalTagItem.name() == m_modifiedTagItem.name()) {
			m_ui->tagNamelineEdit->setText(entry.name());
			tagNameChanged(entry.name());
		}
		if (m_originalTagItem.colour() == m_modifiedTagItem.colour()) {
			if (Colour::isValidColourStr(entry.colour())) {
				m_modifiedTagItem.setColour(entry.colour());
			}
			setPreviewButtonColor(m_modifiedTagItem);
		}
		/* Update original data as the database content has changed. */
		m_originalTagItem.setName(entry.name());
		m_originalTagItem.setColour(entry.colour());
	}
}

void DlgTag::watchTagsDeleted(const Json::Int64StringList &ids)
{
	for (qint64 id : ids) {
		if (Q_UNLIKELY(id < 0)) {
			continue;
		}
		if (m_modifiedTagItem.id() != id) {
			continue;
		}

		/* Close the dialogue. */
		reject();
		break;
	}
}

void DlgTag::watchTagContConnected(void)
{
	if (Q_UNLIKELY(!updateContent())) {
		/* Close the dialogue. */
		reject();
	}

	m_canSaveData = true;
	enableOkButton();
}

void DlgTag::watchTagContDisconnected(void)
{
	m_canSaveData = false;
	enableOkButton();
}

void DlgTag::watchTagContReset(void)
{
	if (Q_UNLIKELY(!updateContent())) {
		/* Close the dialogue. */
		reject();
	}

	enableOkButton();
}

void DlgTag::setPreviewButtonColor(const TagItem &tagItem)
{
	QPalette pal(m_ui->currentColor->palette());
	pal.setColor(QPalette::Button, QColor("#" + tagItem.colour()));
	const QString style = "border-style: outset; background-color: ";
	m_ui->currentColor->setStyleSheet(style + "#" + tagItem.colour());
}

void DlgTag::enableOkButton(void)
{
	m_ui->buttonBox->button(QDialogButtonBox::Ok)->setEnabled(
	    m_canSaveData && !m_modifiedTagItem.name().isEmpty());
}

bool DlgTag::updateContent(void)
{
	if (m_originalTagItem.id() >= 0) {
		/* Editing existing tag. */
		TagContainer *cont = qobject_cast<TagContainer *>(m_tagStorage);
		TagDb *db = qobject_cast<TagDb *>(m_tagStorage);
		TagClient *client = qobject_cast<TagClient *>(m_tagStorage);

		Json::Int64StringList ids = {m_originalTagItem.id()};
		Json::TagEntryList entries;
		if (cont != Q_NULLPTR) {
			cont->getTagData(ids, entries);
		} else if (db != Q_NULLPTR) {
			db->getTagData(ids, entries);
		} else if (client != Q_NULLPTR) {
			client->getTagData(ids, entries);
		}

		if (Q_UNLIKELY(entries.size() != 1)) {
			/* Not data available. */
			return false;
		}

		/* Update dialogue content. */
		const Json::TagEntry entry = entries.at(0);
		{
			m_ui->tagNamelineEdit->setText(entry.name());
			tagNameChanged(entry.name());
		}
		{
			if (Colour::isValidColourStr(entry.colour())) {
				m_modifiedTagItem.setColour(entry.colour());
			}
			setPreviewButtonColor(m_modifiedTagItem);
		}
		/* Update original data as the database content has changed. */
		m_originalTagItem.setName(entry.name());
		m_originalTagItem.setColour(entry.colour());
	}

	return true;
}

bool DlgTag::saveTag(QObject *tagContPtr, const TagItem &tagItem, QWidget *parent)
{
	if (Q_UNLIKELY(Q_NULLPTR == tagContPtr)) {
		Q_ASSERT(0);
		return false;
	}

	TagContainer *tagCont = qobject_cast<TagContainer *>(tagContPtr);
	TagDb *tagDb = qobject_cast<TagDb *>(tagContPtr);
	TagClient *tagClient = qobject_cast<TagClient *>(tagContPtr);

	if (Q_UNLIKELY(tagItem.name().isEmpty())) {
		DlgMsgBox::message(parent, QMessageBox::Critical,
		    tr("Tag error"), tr("Tag name is empty."),
		    tr("Tag wasn't created."), QString());
		return false;
	}

	Q_ASSERT(Colour::isValidColourStr(tagItem.colour()));

	if (tagItem.id() >= 0) {
		const Json::TagEntryList tagEntries({tagItem});
		if (tagCont != Q_NULLPTR) {
			tagCont->updateTags(tagEntries);
		}
		if (tagDb != Q_NULLPTR) {
			tagDb->updateTags(tagEntries);
		}
		if (tagClient != Q_NULLPTR) {
			tagClient->updateTags(tagEntries);
		}
	} else {
		/* Set tag ID to zero. Server complains about missing value. */
		TagItem zeroIdTagItem(tagItem);
		zeroIdTagItem.setId(0);
		const Json::TagEntryList tagEntries({zeroIdTagItem});
		bool ret = false;
		if (tagCont != Q_NULLPTR) {
			ret = tagCont->insertTags(tagEntries);
		}
		if (tagDb != Q_NULLPTR) {
			ret = tagDb->insertTags(tagEntries);
		}
		if (tagClient != Q_NULLPTR) {
			ret = tagClient->insertTags(tagEntries);
		}
		if (!ret) {
			DlgMsgBox::message(parent, QMessageBox::Critical,
			    tr("Tag error"),
			    tr("Cannot write tag with name '%1' to tag storage.")
			        .arg(tagItem.name()),
			    tr("Tag wasn't created."), QString());
			return false;
		}
	}

	return true;
}

void DlgTag::databaseConnectActions(QObject *tagContPtr)
{
	connect(tagContPtr, SIGNAL(tagsUpdated(Json::TagEntryList)),
	    this, SLOT(watchTagsUpdated(Json::TagEntryList)));
	connect(tagContPtr, SIGNAL(tagsDeleted(Json::Int64StringList)),
	    this, SLOT(watchTagsDeleted(Json::Int64StringList)));
	if ((qobject_cast<TagContainer *>(tagContPtr) != Q_NULLPTR) ||
	    (qobject_cast<TagClient *>(tagContPtr) != Q_NULLPTR)) {
		connect(tagContPtr, SIGNAL(connected()),
		    this, SLOT(watchTagContConnected()));
		connect(tagContPtr, SIGNAL(disconnected()),
		    this, SLOT(watchTagContDisconnected()));
		connect(tagContPtr, SIGNAL(reset()),
		    this, SLOT(watchTagContReset()));
	}
}
