#include "projectfilesystemwidget.h"
#include <extensionsystem/pluginmanager.h>
#include <extensionsystem/pluginspec.h>
#include <coreplugin/icore.h>
#include <coreplugin/fileutils.h>
#include <coreplugin/navigationwidget.h>
#include <coreplugin/fileiconprovider.h>
#include <coreplugin/actionmanager/actioncontainer.h>
#include <coreplugin/actionmanager/actionmanager.h>
#include <coreplugin/editormanager/ieditor.h>
#include <coreplugin/editormanager/editormanager.h>
#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/projecttreewidget.h>
#include <projectexplorer/projecttree.h>
#include <projectexplorer/project.h>
#include <projectexplorer/projectnodes.h>
#include <projectexplorer/session.h>
#include <utils/utilsicons.h>
#include <utils/macroexpander.h>
#include <QApplication>
#include <QDesktopServices>
#include <QMessageBox>
#include <QInputDialog>
#include <QScrollBar>
#include <QClipboard>

QFileInfo projectfs_menu_target;


ProjectFilesystemWidget::ProjectFilesystemWidget(QWidget * parent): QWidget(parent) {
	setupUi(this);
	int is = style()->pixelMetric(QStyle::PM_ButtonIconSize, 0, this);
	label->setFixedSize(is, is);
	buttonClear->setIcon(Utils::Icons::CLEAN.icon());
	buttonExpand->setIcon(Utils::Icons::EXPAND.icon());
	buttonCollapse->setIcon(Utils::Icons::COLLAPSE.icon());
	actionOpen_here->setIcon(Utils::Icons::OPENFILE.icon());
	actionOpen_external->setIcon(Utils::Icons::OPENFILE.icon());
	actionShow_external->setIcon(Core::FileIconProvider::icon(QFileIconProvider::Folder));
	actionCopy_name->setIcon(Utils::Icons::COPY.icon());
	actionCopy_path->setIcon(Utils::Icons::COPY.icon());
	popup_menu.addActions(QList<QAction*>() << actionOpen_here << actionOpen_external << actionShow_external << actionOpen_terminal);
	popup_menu.addSeparator();
	popup_menu.addActions(QList<QAction*>() << actionCopy_name << actionCopy_path);
	proj_plug = 0;
	//connect(ProjectExplorer::ProjectTree::instance(), SIGNAL(subtreeChanged(ProjectExplorer::FolderNode*)), this, SLOT(projectsChanged()));
	connect(ProjectExplorer::SessionManager::instance(), SIGNAL(startupProjectChanged(ProjectExplorer::Project *)), this, SLOT(startupProjectChanged()));
	connect(ProjectExplorer::SessionManager::instance(), SIGNAL(projectAdded(ProjectExplorer::Project*)), this, SLOT(projectsChanged()));
	connect(ProjectExplorer::SessionManager::instance(), SIGNAL(projectDisplayNameChanged(ProjectExplorer::Project*)), this, SLOT(projectsChanged()));
	connect(ProjectExplorer::SessionManager::instance(), SIGNAL(projectRemoved(ProjectExplorer::Project*)), this, SLOT(projectsChanged()));
	//connect(ProjectExplorer::SessionManager::instance(), SIGNAL(), this, SLOT(startupProjectChanged()));
	connect(Core::EditorManager::instance(), SIGNAL(currentEditorChanged(Core::IEditor*)), this, SLOT(fileChanged()));
	projectsChanged();
}


void ProjectFilesystemWidget::setCurrentFilter(const FilterDialog::Filter & v) {
	cur_filter = v;
	projectsChanged();
}


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


void ProjectFilesystemWidget::createTree(QTreeWidgetItem * ti, const QString & dir) {
	QFileInfoList fl = QDir(dir).entryInfoList(QDir::AllEntries | QDir::NoDotAndDotDot, QDir::LocaleAware | QDir::DirsFirst);
	for (QFileInfo i: fl) {
		QString nit = i.fileName();
		if (i.isDir()) {
			if (!cur_filter.filterDir(nit))
				continue;
		} else {
			if (!cur_filter.filterFile(nit))
				continue;
		}
		QTreeWidgetItem * ni = new QTreeWidgetItem();
		ni->setText(0, nit);
		ni->setIcon(0, Core::FileIconProvider::icon(i));
		ni->setData(0, Qt::UserRole, i.absoluteFilePath());
		ni->setData(0, Qt::UserRole + 1, i.isDir());
		item_map[i.absoluteFilePath()] = ni;
		if (i.isDir()) {
			createTree(ni, dir + QDir::separator() + i.fileName());
		}
		ti->addChild(ni);
	}
	//if (ti->childCount() == 0) delete ti;
}


bool ProjectFilesystemWidget::filterTree(QTreeWidgetItem * ti, const QString & filter) {
	bool ret = false;
	for (int i = 0; i < ti->childCount(); ++i) {
		QTreeWidgetItem * ci = ti->child(i);
		QString cit = ci->text(0);
		if (ci->data(0, Qt::UserRole + 1).toBool()) {
			if (!filterTree(ci, filter)) {
				ci->setHidden(true);
				continue;
			}
			ci->setHidden(false);
			ret = true;
		} else {
			bool f = false;
			if (filter.isEmpty()) {
				f = true;
			} else {
				f = f || cit.contains(filter);
			}
			ci->setHidden(!f);
			if (f) ret = true;
		}
	}
	return ret;
}


void ProjectFilesystemWidget::filter() {
	QString f = lineFilter->text();
	for (int i = 0; i < tree->topLevelItemCount(); ++i) {
		QTreeWidgetItem * ti = tree->topLevelItem(i);
		filterTree(ti, f);
	}
}


void ProjectFilesystemWidget::rememberExpanded(QTreeWidgetItem * ti) {
	//QMessageBox::information(0, ti->data(0, Qt::UserRole).toString(), QString::number(ti->childCount()));
	for (int i = 0; i < ti->childCount(); ++i) {
		QTreeWidgetItem * ci = ti->child(i);
		if (ci->data(0, Qt::UserRole + 1).toBool()) {
			if (ci->isExpanded())
				last_expanded << ci->data(0, Qt::UserRole).toString();
			rememberExpanded(ci);
		}
	}
}


void ProjectFilesystemWidget::restoreExpanded(QTreeWidgetItem * ti) {
	for (int i = 0; i < ti->childCount(); ++i) {
		QTreeWidgetItem * ci = ti->child(i);
		if (ci->data(0, Qt::UserRole + 1).toBool()) {
			if (last_expanded.contains(ci->data(0, Qt::UserRole).toString()))
				ci->setExpanded(true);
			restoreExpanded(ci);
		}
	}
}


void ProjectFilesystemWidget::setExtVariable() {
}


void ProjectFilesystemWidget::projectsChanged() {
	last_expanded.clear();
	item_map.clear();
	int spos = tree->verticalScrollBar()->value();
	rememberExpanded(tree->invisibleRootItem());
	tree->clear();
	QApplication::setOverrideCursor(Qt::WaitCursor);
	QList<ProjectExplorer::Project *> pl = ProjectExplorer::SessionManager::projects();
	for (ProjectExplorer::Project * p: pl) {
		QTreeWidgetItem * ri = new QTreeWidgetItem();
		QString dir = p->projectDirectory().toString();
		ri->setText(0, p->displayName());
		QFile logo(dir + "/logo.png");
		if (logo.exists())
			ri->setIcon(0, QIcon(logo.fileName()));
		else
			ri->setIcon(0, Core::FileIconProvider::icon(QFileIconProvider::Folder));
		ri->setData(0, Qt::UserRole, dir);
		ri->setData(0, Qt::UserRole + 1, true);
		createTree(ri, dir);
		tree->addTopLevelItem(ri);
	}
	startupProjectChanged();
	fileChanged();
	filter();
	restoreExpanded(tree->invisibleRootItem());
	QApplication::restoreOverrideCursor();
	qApp->processEvents();
	tree->verticalScrollBar()->setValue(spos);
}


void ProjectFilesystemWidget::filterClicked() {
	filter_dialog.setFilter(cur_filter);
	if (filter_dialog.exec() == QDialog::Rejected) return;
	setCurrentFilter(filter_dialog.filter());
}


void ProjectFilesystemWidget::fileChanged() {
	Core::IDocument * cd = Core::EditorManager::instance()->currentDocument();
	if (!cd) return;
	QString np = cd->filePath().toString();
	QTreeWidgetItem * ti = item_map.value(np);
	if (!ti) return;
	tree->setCurrentItem(ti);
	tree->expandItem(ti);
}


void ProjectFilesystemWidget::startupProjectChanged() {
	ProjectExplorer::Project * sp = ProjectExplorer::SessionManager::startupProject();
	QFont f(tree->font()), bf(f);
	bf.setBold(true);
	for (int i = 0; i < tree->topLevelItemCount(); ++i) {
		QTreeWidgetItem * ti = tree->topLevelItem(i);
		ti->setFont(0, f);
		if (!sp) continue;
		if (sp->projectDirectory().toString() == ti->data(0, Qt::UserRole).toString())
			ti->setFont(0, bf);
	}
}


void ProjectFilesystemWidget::on_tree_itemDoubleClicked(QTreeWidgetItem * item, int) {
	if (!item) return;
	QString afp = item->data(0, Qt::UserRole).toString();
	bool dir = item->data(0, Qt::UserRole + 1).toBool();
	if (dir) return;
	if (afp.isEmpty()) return;
	Core::EditorManager::openEditor(afp);
}


void ProjectFilesystemWidget::on_lineFilter_textChanged(const QString & ) {
	filter();
}


void ProjectFilesystemWidget::on_tree_itemClicked(QTreeWidgetItem * item, int column) {
	projectfs_menu_target = QFileInfo();
	if (!item) {
		setExtVariable();
		return;
	}
	projectfs_menu_target = QFileInfo(item->data(0, Qt::UserRole).toString());
	setExtVariable();
}


void ProjectFilesystemWidget::on_tree_customContextMenuRequested(const QPoint & pos) {
	projectfs_menu_target = QFileInfo();
	QTreeWidgetItem * item = tree->itemAt(pos);
	//QMessageBox::information(this, "", QString::number(index.row()));
	if (!item) {
		setExtVariable();
		return;
	}
	projectfs_menu_target = QFileInfo(item->data(0, Qt::UserRole).toString());
	setExtVariable();
	actionOpen_here->setEnabled(!projectfs_menu_target.isDir());
	actionOpen_external->setEnabled(!projectfs_menu_target.isDir());
	popup_menu.popup(tree->mapToGlobal(pos));
}


void ProjectFilesystemWidget::on_actionOpen_here_triggered() {
	if (projectfs_menu_target.path().isEmpty()) return;
	Core::EditorManager::openEditor(projectfs_menu_target.absoluteFilePath(), Core::Constants::K_DEFAULT_TEXT_EDITOR_ID);
}


void ProjectFilesystemWidget::on_actionOpen_external_triggered() {
	if (projectfs_menu_target.path().isEmpty()) return;
	QString wd = QDir::current().absolutePath();
	QDir::setCurrent(projectfs_menu_target.absoluteDir().path());
	QDesktopServices::openUrl(QUrl::fromLocalFile(projectfs_menu_target.absoluteFilePath()));
	QDir::setCurrent(wd);
}


void ProjectFilesystemWidget::on_actionShow_external_triggered() {
	if (projectfs_menu_target.path().isEmpty()) return;
	Core::FileUtils::showInGraphicalShell(Core::ICore::mainWindow(), projectfs_menu_target.absoluteFilePath());
}


void ProjectFilesystemWidget::on_actionOpen_terminal_triggered() {
	if (projectfs_menu_target.path().isEmpty()) return;
	Core::FileUtils::openTerminal(QDir(projectfs_menu_target.absoluteFilePath()).path());
}


void ProjectFilesystemWidget::on_actionCopy_name_triggered() {
	if (projectfs_menu_target.path().isEmpty()) return;
	QApplication::clipboard()->setText(projectfs_menu_target.fileName());
}


void ProjectFilesystemWidget::on_actionCopy_path_triggered() {
	if (projectfs_menu_target.path().isEmpty()) return;
	QApplication::clipboard()->setText(projectfs_menu_target.absoluteFilePath());
}
