/***************************************************************************
 *   Copyright (C) 2003-2007 by Spiros Georgaras <sng@hellug.gr>           *
 *                                                                         *
 *   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.                                   *
 *                                                                         *
 *   This program is distributed in the hope that it will be useful,       *
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of        *
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         *
 *   GNU General Public License for more details.                          *
 *                                                                         *
 *   You should have received a copy of the GNU General Public License     *
 *   along with this program; if not, write to the                         *
 *   Free Software Foundation, Inc.,                                       *
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.         *
 ***************************************************************************/
#include <qapplication.h>
#include "dirsdata.h"
//================================
dirsData::dirsData(){
	hasBeenSorted=FALSE;
	sortID=FALSE;
	mPath=QString::null;
	mFilter=-1;
}
//================================
dirsData::~dirsData(){
	delete [] ren;
	delete [] sort;
}
//================================
// void dirsData::setPath(QString path,const QString &nameFilter,int filterSpec){
void dirsData::setPath(QString path,const QString &nameFilter,QDir::Filters filterSpec){
	int mItems=0;
  //if(!mPath.isEmpty()) delete [] files;
  //find item numbers
	QDir d;
	d.cd(path);
	d.setFilter( filterSpec );
	d.setSorting( QDir::Name );
// 	d.setNameFilter(nameFilter); old impl
	d.setNameFilters(QStringList(nameFilter));
	
	const QFileInfoList list = d.entryInfoList();
	QFileInfo fi;
	for (int i = 0; i < list.size(); ++i) {
		fi=list.at(i);
		if(fi.fileName()=="." || fi.fileName()=="..") mItems--;
		mItems++;
	}
// 	const QFileInfoList *list = d.entryInfoList();
// 	QFileInfoListIterator it( *list );
// 	QFileInfo *fi;
// 	while ( (fi = it.current()) != 0 ) {
// 		if(fi->fileName()=="." || fi->fileName()=="..") mItems--;
// 		mItems++;
// 		++it;
// 	}
	
	
  // set up class filesData
	setItems(mItems);
  // initialize class filesData
	mItems=0;
	
	const QFileInfoList list1 = d.entryInfoList();
	QFileInfo fi1;
	for (int i = 0; i < list.size(); ++i) {
		fi1=list1.at(i);
		if(fi1.fileName()=="." || fi1.fileName()==".."){
			mItems--;
		}else{
			files[mItems].setFile(fi1.filePath());
			//qWarning("dirsData::setPath - setting %s",fi1->filePath().toLocal8Bit().constData());
		}
		mItems++;
	}
	
// 	const QFileInfoList *list1 = d.entryInfoList();
// 	QFileInfoListIterator it1( *list1 );
// 	QFileInfo *fi1;
// 	while ( (fi1 = it1.current()) != 0 ) {
// 		if(fi1->fileName()=="." || fi1->fileName()==".."){
// 			mItems--;
// 		}else{
// 			files[mItems].setFile(fi1->filePath());
// 			//qWarning("dirsData::setPath - setting %s",fi1->filePath().toLocal8Bit().constData());
// 		}
// 		mItems++;
// 		++it1;
// 	}
	
	
	mPath=path;
	mFilter=filterSpec;
	mNameFilter=nameFilter;
	canRename();
	getType();
}
//================================
QString dirsData::path(void){
	return mPath;
}
//================================
// void dirsData::setFilter(int filterSpec){
void dirsData::setFilter(QDir::Filters filterSpec){
	if(mFilter!=filterSpec){
		if(!mPath.isEmpty()) setPath(mPath,mNameFilter,filterSpec);
	}
	mFilter=filterSpec;
}
//================================
int dirsData::filter(void){
	return mFilter;
}
//================================
int dirsData::setLink(filesData * b){
	if(b->items()!=-1){
		ren=new newFile[numOfFiles];
		if(ren==NULL) return -1;
		for(int k=0;k<numOfFiles;k++){
			ren[k].oldFileName=files[k].filePath();
			ren[k].newFileName=files[k].filePath();
// 			ren[k].oldName=files[k].baseName(TRUE); old impl (could use completeBaseName?)
			ren[k].oldName=files[k].baseName();
// 			ren[k].oldExtension=files[k].extension(FALSE); old impl (could use completeSuffix?)
			ren[k].oldExtension=files[k].suffix();
// 			qWarning("dirsData::setLink() - ren[k].oldFileName = %s",ren[k].oldFileName.toLocal8Bit().constData());
// 			qWarning("dirsData::setLink() - ren[k].oldName = %s",ren[k].oldName.toLocal8Bit().constData());
// 			qWarning("dirsData::setLink() - ren[k].oldExtension = %s",ren[k].oldExtension.toLocal8Bit().constData());
// 			qWarning("dirsData::setLink() - b->getType() = %d",b->getType());
			if(b->getType()==2)
				if(!ren[k].oldExtension.isEmpty()){
					ren[k].oldName=ren[k].oldName+"."+ren[k].oldExtension;
					ren[k].oldExtension=QString::null;
			}
// 			qWarning("dirsData::setLink() - fixed ren[k].oldExtension = %s",ren[k].oldExtension.toLocal8Bit().constData());
// 			qWarning("dirsData::setLink() - fixed ren[k].oldName = %s",ren[k].oldName.toLocal8Bit().constData());
			ren[k].newName=ren[k].oldName;
			ren[k].newExtension=ren[k].oldExtension;
			if(files[k].isDir()) ren[k].isDir=TRUE;
			else ren[k].isDir=FALSE;
			ren[k].selected=FALSE;
		}
		for(int k=0;k<numOfFiles;k++){
			for(int i=0;i<b->items();i++){
				if(!ren[k].selected){
					if(b->files[i].filePath()==ren[k].oldFileName){
						ren[k].selected=TRUE;
						ren[k].iconID=0;
					}else{
						ren[k].selected=FALSE;
						ren[k].iconID=-1;
					}
				}
			}
		}
	}
	return 0;
}

//================================
int dirsData::setFilesInDir(bool select){
	if(numOfFiles>0){
		ren=new newFile[numOfFiles];
		if(ren==NULL)
			return -1;
		for(int k=0;k<numOfFiles;k++){
			resetFileName(k);
			ren[k].selected=select;
			if(select)
				ren[k].iconID=0;
			else
				ren[k].iconID=-1;
		}
	}
	return 0;
}
//================================
void dirsData::resetFileName(int k){
// 	qWarning("\"%s\"",ren[k].oldFileName.toLocal8Bit().constData());
	ren[k].oldFileName=files[k].filePath();
// 	qWarning("====== resetFileName -> files[k].filePath() = %s",files[k].filePath().toLocal8Bit().constData());
// 	qWarning("       \"%s\"",ren[k].oldFileName.toLocal8Bit().constData());
	ren[k].newFileName=files[k].filePath();
// 	ren[k].oldName=files[k].baseName(TRUE); old impl (could use completeBaseName?)
	ren[k].oldName=files[k].baseName();
// 	ren[k].oldExtension=files[k].extension(FALSE); old impl (could use completeSuffix?)
	ren[k].oldExtension=files[k].suffix();
// 	qWarning("dirsData::resetFileName() - ren[k].oldFileName = %s",ren[k].oldFileName.toLocal8Bit().constData());
// 	qWarning("dirsData::resetFileName() - ren[k].oldName = %s",ren[k].oldName.toLocal8Bit().constData());
// 	qWarning("dirsData::resetFileName() - ren[k].oldExtension = %s",ren[k].oldExtension.toLocal8Bit().constData());
// 	qWarning("dirsData::resetFileName() - b->getType() = %d",getType());
	if(files[k].isDir())
		if(!ren[k].oldExtension.isEmpty()){
			ren[k].oldName=ren[k].oldName+"."+ren[k].oldExtension;
			ren[k].oldExtension=QString::null;
	}
// 	qWarning("dirsData::resetFileName() - fixed ren[k].oldExtension = %s",ren[k].oldExtension.toLocal8Bit().constData());
// 	qWarning("dirsData::resetFileName() - fixed ren[k].oldName = %s",ren[k].oldName.toLocal8Bit().constData());
	ren[k].newName=ren[k].oldName;
	ren[k].newExtension=ren[k].oldExtension;
	if(files[k].isDir()) ren[k].isDir=TRUE;
	else ren[k].isDir=FALSE;
}
//================================
int dirsData::getSorted(int i){
	if(sortID) return sort[i]; //return i; //return sort[i];
	return i;
}
//================================
int dirsData::setSortValue(bool state){
	sortID=state;
	if(!hasBeenSorted){
		int k=0,adding=0,max=0,maxID=0;
		bool isEqual=TRUE,toTwo=FALSE;
		QString toRef[3]={"","",""};
		QChar * tchar=new QChar[items()];
		if(tchar==NULL) return -1;
		sort=new int[items()];
		if(sort==NULL){
			delete [] tchar;
			return -1;
		}
		for(int i=0;i<items();i++){
			sort[i]=i;
			tchar[i]='\0';
		}
		for(int i=0,l=0;i<items();i++)
			if(ren[i].selected){
				int j=ren[i].oldName.length();
				if(max<j){
					max=j;
					maxID=l;
				}
				l++;
			}
		while(max>k){
			for(int i=0,l=0;i<items();i++) if(ren[i].selected){
				isEqual=TRUE;
				if(ren[i].oldName.length()>k){
					tchar[l]=ren[i].oldName.at(k);
// 		qWarning("dirsData::setSortValue() -- 1.2  --  oldName = %s , ren[%d].oldName.at(%d) = '%c'",ren[i].oldName.toLocal8Bit().constData(),i,k,ren[i].oldName.at(k).toLatin1());
				}else{
					tchar[l]='\0';
// 		qWarning("dirsData::setSortValue() -- 1.2  --  oldName = %s , ren[%d].oldName.at(%d) = '/0'",ren[i].oldName.toLocal8Bit().constData(),i,k);
				}
// 		qWarning("tchar[%d] = %c",l,tchar[l].toLatin1());
				if(l>0 && tchar[l]!=tchar[l-1]) isEqual=FALSE;
				l++;
			}
	//qWarning("----- isEqual = %d",isEqual);
			if(isEqual){
				toRef[adding]+=tchar[maxID];
		//qWarning("toRef[%d].append(tchar[0])= %s",adding,toRef[adding].toLocal8Bit().constData());
			}else{
				adding=2;
				if(tchar[maxID].isDigit() && !toTwo){
					toRef[1].append(tchar[maxID]);
				}else{
					toRef[adding].append(tchar[maxID]);
					toTwo=TRUE;
				}
		//qWarning("toRef[1].append(tchar[0]) = %s",toRef[1].toLocal8Bit().constData());
			}
			k++;
		}
		delete [] tchar;
//qWarning("1. %s\n2. %s\n3. %s",toRef[0].toLocal8Bit().constData(),toRef[1].toLocal8Bit().constData(),toRef[2].toLocal8Bit().constData());
		QString a="",b="";
		for(int i=toRef[0].length()-1;i>=0;i--){
			QChar s=toRef[0].at(i);
	//qWarning("s = %c",s.toLocal8Bit().constData());
			if(s.isDigit() && a.isEmpty()) b.prepend(s);
			else a.prepend(s);
	//qWarning("a = %s, b = %s",a.toLocal8Bit().constData(),b.toLocal8Bit().constData());
		}
//qWarning("a = %s, b = %s",a.toLocal8Bit().constData(),b.toLocal8Bit().constData());
		toRef[0]=a;toRef[1].prepend(b);
//qWarning("1. %s\n2. %s\n3. %s",toRef[0].toLocal8Bit().constData(),toRef[1].toLocal8Bit().constData(),toRef[2].toLocal8Bit().constData());
	//return;
		a="";b="";
// 		for(int i=0;(uint)i<toRef[2].length();i++){ old impl
		for(int i=0;i<toRef[2].length();i++){
			QChar s=toRef[2].at(i);
	//qWarning("  s = %c",s.toLocal8Bit().constData());
	//qWarning("isDigit = %d, %d",s.isDigit(),TRUE);
			if(s.isDigit() && b.isEmpty()) a+=s;
			else b+=s;
	//qWarning("  a = %s\n  b = %s",a.toLocal8Bit().constData(),b.toLocal8Bit().constData());
		}
		toRef[1].append(a);
		toRef[2]=b;
	//qWarning("1. %s\n2. %s\n3. %s",toRef[0].toLocal8Bit().constData(),toRef[1].toLocal8Bit().constData(),toRef[2].toLocal8Bit().constData());
	//return;
	//for(int i=0;(uint)i<toRef[0].length();i++) if(!toRef[1].at(i).isDigit()) return;
		toRef[1]="[0-9]*";
	//qWarning("1. %s\n2. %s\n3. %s",toRef[0].toLocal8Bit().constData(),toRef[1].toLocal8Bit().constData(),toRef[2].toLocal8Bit().constData());
		QRegExp searchIt,getNum;
	//if(ren[0].oldExtension.isEmpty()){
		a=toRef[0]+"([0-9]*)"+toRef[2];
		b=toRef[0]+toRef[1]+toRef[2];
/*	}else{
		a=toRef[0]+"([0-9]*)"+toRef[2]+"."+ren[0].oldExtension;
		b=toRef[0]+toRef[1]+toRef[2]+"."+ren[0].oldExtension;
	}*/
// 	qWarning("a = %s",a.toLocal8Bit().constData());
// 	qWarning("b = %s",b.toLocal8Bit().constData());
		searchIt.setPattern(b);
// 		searchIt.setWildcard(TRUE); old impl
		searchIt.setPatternSyntax(QRegExp::Wildcard);
// 		searchIt.setCaseSensitive(TRUE); old impl
		searchIt.setCaseSensitivity(Qt::CaseSensitive);
		getNum.setPattern(a);
// 		getNum.setWildcard(TRUE); old impl
		getNum.setPatternSyntax(QRegExp::Wildcard);
//		getNum.setCaseSensitive(TRUE); old impl
		getNum.setCaseSensitivity(Qt::CaseSensitive);
		getNum.setMinimal(TRUE);
	//qWarning("RegExp = %s",searchIt.toLocal8Bit().constData());
	//for(int i=0,l=0;i<items();i++) if(ren[i].selected){
		int * ll=new int [items()];
		if(ll==NULL) return -1;
		long * num = new long [items()];
		if(num==NULL){
			delete[] ll;
			return -1;
		}
	//qWarning("%s %s\n",toRef[0].toLocal8Bit().constData(),toRef[2].toLocal8Bit().constData());
		for(int i=0;i<items();i++){
			QString toSearch=ren[i].oldName;
		/*if(!ren[i].oldExtension.isEmpty()){
			toSearch+=".";
			toSearch+=ren[i].oldExtension;
		}*/
// 			if((searchIt.search(toSearch))==0){ old impl
			if((searchIt.indexIn(toSearch))==0){
		  //qWarning("valid = %s",ren[i].oldName.toLocal8Bit().constData());
				ll[i]=i;
				QString tmp=ren[i].oldName;
				tmp.replace(QRegExp(QRegExp::escape(toRef[0])),"");
				tmp.replace(QRegExp(QRegExp::escape(toRef[2])),"");
		//qWarning("number = %s",tmp.toLocal8Bit().constData());
				num[i]=tmp.toLong();
		//qWarning("number = %l",num[i]);
			}else{
				ll[i]=-1;num[i]=-1;
			}
		}
	//sort arrays
		int i,j;
		for(i=0;i<items();i++) if(ll[i]!=-1){
			long min=num[i];
			int id=i;
			for(j=i+1;j<items();j++) if(ll[j]!=-1 && min>=num[j]){
				min=num[j];
				id=j;
			}
			int tmpID=ll[i];
			int tmpLong=num[i];
			ll[i]=ll[id];
			num[i]=min;
			ll[id]=tmpID;
			num[id]=tmpLong;
		}
		for(int i=0;i<items();i++) if(ll[i]!=-1) sort[i]=ll[i];
		delete [] ll;delete [] num;
		hasBeenSorted=TRUE;
	}
	return 0;
}


void dirsData::resetHasbeenSorted(){
	hasBeenSorted=false;
}

int dirsData::numOfSlectedItems(){
	int res=0;
	for(int i=0;i<items();i++)
		if(ren[i].selected) res++;
	return res;
}

