//TASK read project path Settings::instance()->setValue(plugin->name(), key, value);
//TASK provide decorations(icons, etc) - model role (see QVariant QFileSystemModel::data, Qt::DecorationRole)

#include "FMPlugin.h"

#include <QCompleter>
#include <QHeaderView>
#include <QInputDialog>
#include <QLineEdit>
#include <QMessageBox>
#include <QMenu>
#include <QAction>
#include <QToolBar>
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QCheckBox>

#include <Log.h>
#include <MainSettings.h>
#include <PluginSettings.h>
#include <EditorSettings.h>

#include "ManageDlg.h"
#include "TreeView.h"
#include "documentationmodel.h"

FMPlugin::FMPlugin() : QObject(), JuffPlugin() {

}

void FMPlugin::init(){
     sortColumn = PluginSettings::getInt(this, "sortColumn", 0);

    w_ = new QWidget();
    w_->setWindowTitle(tr("Project"));

    model_ = new DocumentationModel(reinterpret_cast<DocumentationProject*>(api()->currentProject()), w_);
    model_->setRootPath("/");
    model_->setNameFilters(QStringList{"*.remarkup"});
    model_->setNameFilterDisables(false);
    model_->setReadOnly(false);

    //        filter |= QDir::Hidden;
    //    model_->setFilter(filter);

    tree_ = new TreeView(this, model_);
	tree_->setModel(model_);
//	tree_->setAllColumnsShowFocus(true);
    tree_->sortByColumn(sortColumn, Qt::AscendingOrder);
    tree_->setSortingEnabled(true);
    tree_->setSelectionMode(QAbstractItemView::SingleSelection);

        //drag & drop
    tree_->setDragEnabled(true);
    tree_->viewport()->setAcceptDrops(true);
    tree_->setDropIndicatorShown(true);
    tree_->setDragDropMode(QAbstractItemView::InternalMove);
    tree_->setDragDropOverwriteMode(false);

    tree_->setEditTriggers(QTreeView::EditKeyPressed);
    connect(model_, &DocumentationModel::fileMoved, this, &FMPlugin::onFileMoved);
    connect(model_, &QFileSystemModel::fileRenamed, this, &FMPlugin::onFileRenamed);

	tree_->header()->resizeSection(0, 180);
	tree_->header()->resizeSection(1, 80);
	tree_->header()->resizeSection(2, 60);
	tree_->header()->resizeSection(3, 180);
	tree_->initMenu();

        tree_->setRootIsDecorated(true);
        tree_->setItemsExpandable(true);

//TOOLBAR:
   // QToolBar * toolBar = new QToolBar("File Browser Tools", w_);
    //backBtn_ = toolBar->addAction(QIcon::fromTheme("go-previous", QIcon(":icon_back")), tr("Go Back"), this, SLOT(back()));

    /*
        if ( Settings::instance()->valueExists(plugin->name(), key) )
            return Settings::instance()->stringValue(plugin->name(), key);
    */

    pathEd_ = new QLineEdit();
    pathEd_->setCompleter(new QCompleter(model_));
    connect(pathEd_, SIGNAL(returnPressed()), SLOT(onNewProjectRoot()));

	QVBoxLayout* vBox = new QVBoxLayout();
	vBox->setMargin(0);
	vBox->setSpacing(2);

//	vBox->addWidget(toolBar);
    vBox->addWidget(pathEd_);
	vBox->addWidget(tree_);

	w_->setLayout(vBox);

	connect(tree_, SIGNAL(doubleClicked(const QModelIndex&)), SLOT(itemDoubleClicked(const QModelIndex&)));
	connect(&fsWatcher_, SIGNAL(directoryChanged(const QString&)), SLOT(onDirChanged(const QString&)));

       cd("/private/prg/code/xreate/documentation");

	applySettings();
}

FMPlugin::~FMPlugin() {
	w_->deleteLater();
}

QString FMPlugin::name() const {
    return "Project";
}

QString FMPlugin::title() const {
    return tr("Project");
}

QString FMPlugin::targetEngine() const {
	return "all";
}

QString FMPlugin::description() const {
    return "List of project files";
}

QWidgetList FMPlugin::dockList() const {
	QWidgetList wList;
	wList << w_;
	return wList;
}

bool FMPlugin::dockVisible(QWidget* w) const {
	if ( w == w_ ) {
		return true;
	}
	else {
		return JuffPlugin::dockVisible(w);
	}
}

void FMPlugin::cd(const QString& path) {
	if ( QFileInfo(path).isDir() ) {
		// remove currently watching paths
		QStringList dirs = fsWatcher_.directories();
		if ( !dirs.isEmpty() ) {
			fsWatcher_.removePaths(dirs);
		}

        tree_->setRootIndex(model_->index(path));
		pathEd_->setText(path);
		pathEd_->setToolTip(path);

		// add new current path for watching
		fsWatcher_.addPath(path);
	}
}

void FMPlugin::itemDoubleClicked(const QModelIndex& index) {
	QString path = model_->filePath(index);

	if ( QFileInfo(path).isDir() ) {
		cd(path);
	}
	else {
		api()->openDoc(path);
	}
}

void FMPlugin::onDirChanged(const QString&) {
}

/*
void FMPlugin::curFileDir() {
	Juff::Document* doc = api()->currentDocument();
	if ( !doc->isNull() && !doc->isNoname() ) {
		cd(QFileInfo(doc->fileName()).absolutePath());
	}
}
*/


/*
void FMPlugin::newDir() {
	QString newDirName = QInputDialog::getText(tree_, tr("New directory"), tr("Directory name"));
    if (newDirName.isEmpty())
        return;

    QDir curDir(model_->filePath(tree_->rootIndex()));
    if ( !curDir.mkdir(newDirName) ) {
        QMessageBox::warning(tree_, tr("Warning"),
                             tr("Couldn't create a dir named '%1'").arg(newDirName));
    }
}
*/


void FMPlugin::onNewProjectRoot() {
	if ( QFileInfo(pathEd_->text()).isDir() )
		cd(pathEd_->text());
//	else
//		pathEd_->setText(modelFilesystem->filePath(tree_->rootIndex()));
}

void FMPlugin::onDocSaved(const QString& fileName) {
    Q_UNUSED(fileName);
}

void FMPlugin::applySettings() {
//	QPalette plt = tree_->palette();
//	plt.setColor(QPalette::Base, EditorSettings::get(EditorSettings::DefaultBgColor));
//	plt.setColor(QPalette::Text, EditorSettings::get(EditorSettings::DefaultFontColor));
////	plt.setColor(QPalette::Highlight, EditorSettings::get(EditorSettings::SelectionBgColor));
////	plt.setColor(QPalette::HighlightedText, TextDocSettings::selectionTextColor());
//	tree_->setPalette(plt);
//	pathEd_->setPalette(plt);

//	PluginSettings::set(this, "ShowAsTree", showAsTree);
//	tree_->setRootIsDecorated(showAsTree);
//	tree_->setItemsExpandable(showAsTree);

//    QDir::Filters filter = QDir::AllDirs | QDir::AllEntries | QDir::NoDotAndDotDot;
//    if (showHidden)
//        filter |= QDir::Hidden;
//    model_->setFilter(filter);
}

QWidget * FMPlugin::settingsPage() const
{
//	QWidget * cfg = new QWidget();
//	QVBoxLayout * l = new QVBoxLayout();
//	cfg->setLayout(l);

//	QCheckBox * treeCheckBox = new QCheckBox(tr("Show Directory Structure in a Tree"), cfg);
//	treeCheckBox->setChecked(showAsTree);
//	connect(treeCheckBox, SIGNAL(toggled(bool)), this, SLOT(treeCheckBox_toggled(bool)));

//    QCheckBox *showHiddenBox = new QCheckBox(tr("Show Hidden Files and Directories"), cfg);
//    showHiddenBox->setChecked(showHidden);
//    connect(showHiddenBox, SIGNAL(toggled(bool)), this, SLOT(showHiddenBox_toggled(bool)));

//	l->addWidget(treeCheckBox);
//    l->addWidget(showHiddenBox);
//	l->addItem(new QSpacerItem(1, 1, QSizePolicy::Minimum, QSizePolicy::MinimumExpanding));
//	return cfg;

    return 0;
}

void
FMPlugin::onFileMoved(const QString &path, const QString &pathOld){
    QStringList docs = api()->docList();
    const QFileInfo& fileInfo(path);

    if ( fileInfo.isDir()){
        //move section
        for(QString& file: docs) {
            if (file.left(pathOld.length()).compare(pathOld) == 0){
                    //file affected
                Juff::Document* docUpdated = api()->document(file);

                const QString& fileNewName = file.replace(0, pathOld.length(), path);
                docUpdated->setFileName(fileNewName);
            }
        }
    } {
        //move topic
        for(const QString& file: docs) {
            if (file.length() == pathOld.length() && file.compare(pathOld) == 0){
                Juff::Document* docUpdated = api()->document(file);
                docUpdated->setFileName(path);
                break;
            }
        }
    }
}

void
FMPlugin::onFileRenamed(const QString &path, const QString &oldName, const QString &newName){
    const QString& fileOldName = path + QDir::separator() + oldName;
    const QString& fileNewName = path + QDir::separator() + newName;

    QStringList docs = api()->docList();

    for(const QString& file: docs) {
        if (file.length() == fileOldName.length() && file.compare(fileOldName) == 0){
            Juff::Document* docUpdated = api()->document(file);
            docUpdated->setFileName(fileNewName);
            break;
        }
    }
}

#if QT_VERSION < 0x050000
Q_EXPORT_PLUGIN2(fm, FMPlugin)
#endif
