#include "StdAfx.h"
#include "MatcapSelectDlg.h"

#include <QMessageBox>
#include <QDir>

#include "PathInfo.h"



MatcapSelectDlg::MatcapSelectDlg(QWidget *parent)
	: QDialog(parent)
{
	ui.setupUi(this);

	InitGroups();

	Qt::WindowFlags flags = windowFlags() & (~Qt::WindowContextHelpButtonHint);
	flags = flags | Qt::WindowMinimizeButtonHint;
	flags = flags | Qt::WindowCloseButtonHint;
	setWindowFlags(flags);
}

MatcapSelectDlg::~MatcapSelectDlg()
{
}

void MatcapSelectDlg::InitGroups(void)
{
	QString dirPath = PathInfo::GetMatCapPresetDirPath();
	QDir d(dirPath);

	QStringList filter;
	QStringList filelist = d.entryList( QDir::Dirs);

	for (QString s : filelist)
	{
		if (s == "." || s == "..")
			continue;

		ui.comboDataGroup->addItem(s);
	}
}

bool MatcapSelectDlg::RebuildList(void)
{
	ui.listImages->blockSignals(true);
	bool suc = RebuildListMain();
	ui.listImages->blockSignals(false);

	return suc;
}

bool MatcapSelectDlg::RebuildListMain(void)
{
	ui.listImages->clear();

	QString dirpath = GetImageDirPath();

	QStringList files;
	GetPresetFiles(dirpath, files);

	if (files.isEmpty())
	{
		QMessageBox::warning(this, "", "No images");
		return false;
	}

	for (const QString& filename : files)
	{
		QString path = dirpath + filename;
		QIcon icon;
		icon.addFile(path);
		bool suc = !icon.isNull();

		QListWidgetItem* obj = new QListWidgetItem(ui.listImages);
		obj->setIcon(icon);
		obj->setText(filename);
		ui.listImages->addItem(obj);
	}

	ui.listImages->setCurrentRow(0);
	ui.listImages->setCurrentRow(-1);

	return true;
}

void MatcapSelectDlg::GetPresetFiles(const QString& dirpath, QStringList& files)
{
	QDir dir;
	dir.setPath(dirpath);
	QStringList filter;
	filter
		<< "*.jpg"
		<< "*.jpeg"
		<< "*.png"
		<< "*.bmp";
	dir.setNameFilters(filter);

	files = dir.entryList();
}

QString MatcapSelectDlg::GetImageDirPath(void) const
{
	if (m_CurrentGroup.isEmpty())
		return "";

	QString dirPath = PathInfo::GetMatCapPresetDirPath();
	dirPath += m_CurrentGroup;
	dirPath += "/";
	return QDir::toNativeSeparators(dirPath);
}

QString MatcapSelectDlg::GetSelectedItemPath(void) const
{
	int i = ui.listImages->currentRow();
	if(i < 0)
		return "";

	QString fname = ui.listImages->item(i)->text();
	if(fname.isEmpty())
		return "";

	return GetImageDirPath() + "\\" + fname;
}

void MatcapSelectDlg::on_buttonBox_accepted()
{
	accept();
}

void MatcapSelectDlg::on_buttonBox_rejected()
{
	reject();
}

void MatcapSelectDlg::on_listImages_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
	emit ListSelectChanged();
}

void MatcapSelectDlg::on_comboDataGroup_currentIndexChanged(int index)
{
	m_CurrentGroup = ui.comboDataGroup->itemText(index);
	RebuildListMain();
}
