/***************************************************************************
 *   Copyright (C) 2001 by Bernd Gehrmann                                  *
 *   bernd@kdevelop.org                                                    *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

#include "removefiledlg.h"

#include <tqcheckbox.h>
#include <tqgroupbox.h>
#include <tqfile.h>
#include <tqlabel.h>
#include <tqlayout.h>
#include <tqpushbutton.h>
#include <tqregexp.h>

#include <kbuttonbox.h>
#include <kdebug.h>
#include <kdialog.h>
#include <ksqueezedtextlabel.h>

#include "autolistviewitems.h"

#include "misc.h"
#include "autoprojectpart.h"
#include "autoprojectwidget.h"
#include "autodetailsview.h"

static bool fileListContains(const TQPtrList<FileItem> &list, const TQString &name)
{
	TQPtrListIterator<FileItem> it(list);
	for (; it.current(); ++it)
		if ((*it)->text(0) == name)
			return true;
	return false;
}


RemoveFileDialog::RemoveFileDialog(AutoProjectWidget *widget, AutoProjectPart* part, SubprojectItem *spitem,
								TargetItem *item, const TQString &filename,
								TQWidget *parent, const char *name)
	: RemoveFileDlgBase(parent, name, true)
{
	removeFromTargetsCheckBox = 0;

	TQStringList targets;

	TQPtrListIterator<TargetItem> it(spitem->targets);
	for (; it.current(); ++it)
		if (fileListContains((*it)->sources, filename))
			targets.append((*it)->name);

	if (targets.count() > 1)
	{
		removeFromTargetsCheckBox = new TQCheckBox( fileGroupBox, "removeFromTargetsCheckBox" );
		removeFromTargetsCheckBox->setMinimumSize( TQSize( 0, 45 ) );
		fileLayout->addWidget( removeFromTargetsCheckBox );

		TQString joinedtargets = "    *" + targets.join("\n    *");
		removeFromTargetsCheckBox->setText ( i18n ( "The file %1 is still used by the following targets:\n%2\n"
												"Remove it from all of them?").arg(filename).arg(joinedtargets) );
        setMinimumSize(TQSize(size().width(), size().height() + removeFromTargetsCheckBox->size().height()*2) );
	}

	removeLabel->setText ( i18n ( "Do you really want to remove <b>%1</b>?" ).arg ( filename ) );

	directoryLabel->setText ( spitem->path );
	if ( item->name.isEmpty() )
		targetLabel->setText ( i18n ( "%1 in %2" ).arg ( item->primary ).arg ( item->prefix ) );
	else
		targetLabel->setText ( item->name );

	connect ( removeButton, TQT_SIGNAL ( clicked() ), this, TQT_SLOT ( accept() ) );
	connect ( cancelButton, TQT_SIGNAL ( clicked() ), this, TQT_SLOT ( reject() ) );

	setIcon ( SmallIcon ( "editdelete.png" ) );

	m_widget = widget;
	m_part = part;
	subProject = spitem;
	target = item;
	fileName = filename;
}


RemoveFileDialog::~RemoveFileDialog()
{}


void RemoveFileDialog::accept()
{
	m_widget->emitRemovedFile ( subProject->path.mid ( m_part->projectDirectory().length() + 1 ) + "/" + fileName );

	TQMap<TQString,TQString> replaceMap;

	if (removeFromTargetsCheckBox && removeFromTargetsCheckBox->isChecked()) {
		TQPtrListIterator<TargetItem> it(subProject->targets);
		for (; it.current(); ++it) {
			if ((*it) != target && fileListContains((*it)->sources, fileName)) {
				FileItem *fitem = static_cast<FileItem*>((*it)->firstChild());
				while (fitem) {
					FileItem *nextitem = static_cast<FileItem*>(fitem->nextSibling());
					if (fitem->text(0) == fileName) {
						TQListView *lv = fitem->listView();
						lv->setSelected(fitem, false);
						(*it)->sources.remove(fitem);
					}
					fitem = nextitem;
				}
				TQString canontargetname = AutoProjectTool::canonicalize((*it)->name);
                                TQString varname;
                                if( (*it)->primary == "PROGRAMS" || (*it)->primary == "LIBRARIES" || (*it)->primary == "LTLIBRARIES" )
                                    varname = canontargetname + "_SOURCES";
                                else
                                    varname = (*it)->prefix + "_" + (*it)->primary;
				TQStringList sources = TQStringList::split(TQRegExp("[ \t\n]"), subProject->variables[varname]);
				sources.remove(fileName);
				subProject->variables[varname] = sources.join(" ");
				replaceMap.insert(varname, fileName);
			}
		}
	}

	TQString fileItemName;
	FileItem *fitem = static_cast<FileItem*>(target->firstChild());
	while (fitem) {
		if (fitem->text(0) == fileName) {
			TQListView *lv = fitem->listView();
			lv->setSelected(fitem, false);
			fileItemName = fitem->name;
			target->sources.remove(fitem);
			break;
		}
		fitem = static_cast<FileItem*>(fitem->nextSibling());
	}
	TQString canontargetname = AutoProjectTool::canonicalize(target->name);
	TQString varname;
	if( target->primary == "PROGRAMS" || target->primary == "LIBRARIES" || target->primary == "LTLIBRARIES" )
	    varname = canontargetname + "_SOURCES";
	else
	    varname = target->prefix + "_" + target->primary;
	TQStringList sources = TQStringList::split(TQRegExp("[ \t\n]"), subProject->variables[varname]);
	sources.remove(fileName);
	subProject->variables[varname] = sources.join(" ");
	replaceMap.insert(varname, fileName);

	AutoProjectTool::removeFromMakefileam(subProject->path + "/Makefile.am", replaceMap);

//  review configuration cleanup in the project file after removing subclassing related source
	TQDomDocument &dom = *(m_part->projectDom());

	TQDomElement el = dom.documentElement();
	TQDomNode el2 = el.namedItem("kdevautoproject");
	TQDomNode el3 = el2.namedItem("subclassing");

	TQDomNode n = el3.firstChild();
	TQValueList<TQDomNode> nodesToRemove;
	while ( !n.isNull() ) {
		TQDomNamedNodeMap attr = n.attributes();
		TQString fpath = subProject->path + TQString("/") + fileItemName;
		TQString relpath = fpath.remove(0, m_part->projectDirectory().length());
		if ((attr.item(0).nodeValue() == relpath)
			|| (attr.item(1).nodeValue() == relpath) )
			nodesToRemove.append(n);
		n = n.nextSibling();
	}
	TQValueList<TQDomNode>::iterator it;
	for ( it = nodesToRemove.begin(); it != nodesToRemove.end(); ++it )
		el3.removeChild(*it);

	if (removeCheckBox->isChecked())
		TQFile::remove(subProject->path + "/" + fileName);

	TQDialog::accept();
}

#include "removefiledlg.moc"
