/*
	QGL TexturesEditor
    Ivan Pelipenko peri4ko@yandex.ru

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU Lesser 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 Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

#include "textures_editor.h"

#include "glmaterial.h"
#include "gltexture_manager.h"
#include "qglview.h"
#include "ui_textures_editor.h"

#include <QInputDialog>
#include <QMessageBox>
#include <qad_types.h>


TexturesEditor::TexturesEditor(QWidget * parent): QWidget(parent) {
	ui = new Ui::TexturesEditor();
	ui->setupUi(this);
	ui->scrollArea->viewport()->setAutoFillBackground(false);
	ui->scrollAreaWidgetContents->setAutoFillBackground(false);
	ui->labelMissed->hide();
	view = 0;
}


void TexturesEditor::assignQGLView(QGLView * v) {
	view = v;
	connect(view->textureManager(), &TextureManager::loadingDone, this, [this]() { showWarning(); });
	connect(view->textureManager(), &TextureManager::filesUsed, this, [this](int count) { ui->labelUsedFiles->setNum(count); });
	showPathes();
}


void TexturesEditor::changeEvent(QEvent * e) {
	QWidget::changeEvent(e);
	switch (e->type()) {
	case QEvent::LanguageChange: ui->retranslateUi(this); break;
	default: break;
	}
}


void TexturesEditor::showPathes() {
	ui->listWidget->clear();
	ui->listWidget->addItems(TextureManager::searchPathes());
}


void TexturesEditor::showWarning() {
	QString mf = QStringList(view->textureManager()->missedFiles().values()).join("\n");
	ui->labelMissed->setText(tr("Missed files:") + "\n" + mf);
	ui->labelMissed->setHidden(mf.isEmpty());
}


void TexturesEditor::setPathes() {
	QStringList pl;
	for (int i = 0; i < ui->listWidget->count(); ++i)
		pl << ui->listWidget->item(i)->text();
	TextureManager::setSearchPathes(pl);
	if (view) view->reloadTextures();
}


void TexturesEditor::on_buttonPathesAdd_clicked() {
	QString p = QFileDialog::getExistingDirectory(nullptr, tr("Select search path"), prev_path);
	if (p.isEmpty()) return;
	prev_path = p;
	if (TextureManager::searchPathes().contains(p)) return;
	ui->listWidget->addItem(p);
	setPathes();
}


void TexturesEditor::on_buttonPathesDelete_clicked() {
	qDeleteAll(ui->listWidget->selectedItems());
	setPathes();
}


void TexturesEditor::on_buttonPathesClear_clicked() {
	ui->listWidget->clear();
	setPathes();
}


void TexturesEditor::on_buttonReload_clicked() {
	if (!view) return;
	view->reloadTextures();
}
