#include "StdAfx.h"
#include "EnvmapSelectDlg.h"

#include <QMessageBox>
#include <QDir>
#include <QFileInfo>

#include "PathInfo.h"



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

EnvmapSelectDlg::~EnvmapSelectDlg()
{
}

void EnvmapSelectDlg::InitGroups(void)
{
	QString dirPath = PathInfo::GetEnvmapPresetDirPath();
	QDir d(dirPath);

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

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

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

void EnvmapSelectDlg::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 EnvmapSelectDlg::GetImageDirPath(void) const
{
	if (m_CurrentGroup.isEmpty())
		return "";

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

QString EnvmapSelectDlg::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 EnvmapSelectDlg::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;
	}

	QStringList filesR;
	for (size_t i = 1; i < files.size(); ++i)
	{
		QString f0 = files[i - 1];
		QString f1 = files[i];

		QString n0 = QFileInfo(f0).baseName();
		QString n1 = QFileInfo(f1).baseName();

		if ((n0 + "_Thumb") != n1)
			continue;

		filesR.push_back(f0);
		i += 1;
	}

	for (const QString& name : filesR)
	{
		QString bname = QFileInfo(name).baseName();
		QString suf = QFileInfo(name).suffix();

		QString path = dirpath + bname + "_Thumb" + "." + suf;
		QIcon icon;
		icon.addFile(path);
		bool suc = !icon.isNull();

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

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