#include "filterdialog.h"
#include <utils/utilsicons.h>
#include <QDir>


FilterDialog::FilterDialog(QWidget * parent): QDialog(parent) {
	setupUi(this);
	toolButton->setIcon(Utils::Icons::CLEAN.icon());
	toolButton_2->setIcon(Utils::Icons::CLEAN.icon());
	toolButton_3->setIcon(Utils::Icons::CLEAN.icon());
	toolButton_4->setIcon(Utils::Icons::CLEAN.icon());
}


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


FilterDialog::Filter FilterDialog::filter() const {
	FilterDialog::Filter ret;
	ret.files_show = getFilters(lineFilesShow);
	ret.files_hide = getFilters(lineFilesHide);
	ret.dirs_show = getFilters(lineDirsShow);
	ret.dirs_hide = getFilters(lineDirsHide);
	return ret;
}

void FilterDialog::setFilter(const FilterDialog::Filter & f) {
	setFilters(lineFilesShow, f.files_show);
	setFilters(lineFilesHide, f.files_hide);
	setFilters(lineDirsShow, f.dirs_show);
	setFilters(lineDirsHide, f.dirs_hide);
}


QStringList FilterDialog::getFilters(QLineEdit * le) const {
	if (!le) return QStringList();
	QStringList ret = le->text().split(",");
	for (int i = 0; i < ret.size(); ++i)
		ret[i] = ret[i].trimmed();
	ret.removeAll("");
	return ret;
}


void FilterDialog::setFilters(QLineEdit * le, QStringList f) {
	if (!le) return;
	le->setText(f.join(","));
}


FilterDialog::Filter::Filter(const QVariant & v) {
	QByteArray ba = v.toByteArray();
	if (ba.isEmpty()) return;
	QDataStream s(ba);
	s >> files_show >> files_hide >> dirs_show >> dirs_hide;
}


QVariant FilterDialog::Filter::toVariant() const {
	QByteArray ba;
	QDataStream s(&ba, QIODevice::ReadWrite);
	s << files_show << files_hide << dirs_show << dirs_hide;
	return QVariant(ba);
}


bool FilterDialog::Filter::filterLogic(const QStringList & fshow, const QStringList & fhide, const QString & path) const {
	if (fshow.isEmpty() && fhide.isEmpty()) return true;
	if (!fhide.isEmpty()) {
		if (QDir::match(fhide, path))
			return false;
		else {
			if (fshow.isEmpty())
				return true;
			else
				return QDir::match(fshow, path);
		}
	}
	if (!fshow.isEmpty())
		return QDir::match(fshow, path);
	return true;
}
