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

#include <QMessageBox>
#include <QDir>

#include "PathInfo.h"



MatcapSelectDlg::MatcapSelectDlg(QWidget *parent)
	: PresetSelectDlg(parent)
{
	InitGroups();
}

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);
	}
}

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::ChangeGroup(int index)
{
	m_CurrentGroup = ui.comboDataGroup->itemText(index);

	ui.listImages->clear();

	QString dirpath = GetImageDirPath();

	QStringList files;
	GetPresetFiles(dirpath, files);

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

	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);
}
