/***************************************************************************
 *   Copyright (C) 2008 by Juergen Thies                                   *
 *   layout@juergenthies.de                                                *
 *                                                                         *
 *   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.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "csv.h"
#include <qfile.h>
#include <qstring.h>
#include <qtextstream.h>
#include "general/drawingfield.h"
#include "elements/pointarray.h"
#include "general/layers.h"
#include "elements/celllist.h"
#include "elements/cell.h"
#include "elements/path.h"
#include "elements/polygon.h"
#include "general/setup.h"
#include "elements/element.h"
#include <qstringlist.h>
#include "layout.h"
#include "elements/pointarray.h"
#include <QFileInfo>


csv::csv(QObject *parent, const char *)
 : QObject(parent)
{
}


csv::~csv()
{
}


void csv::open(QString fileName,drawingField *d){
  csv csvClass;
  csvClass.load(fileName,d,fileOpen);
}

void csv::import(QString fileName,drawingField *d){
  csv csvClass;
  csvClass.load(fileName,d,fileImport);
}

void csv::update(QString fileName,drawingField *d){
  csv csvClass;
  csvClass.load(fileName,d,fileUpdate);
}

void csv::load(QString fileName,drawingField *d,fileOpenType typ){
  if (typ==fileImport) {
  	report.setTitle(tr("Import of CSV-File \"")+fileName+"\"");}
  else if (typ==fileOpen){
	report.setTitle(tr("Open of CSV-File \"")+fileName+"\"");}
  else if (typ==fileUpdate){
	report.setTitle(tr("Update with CSV-File \"")+fileName+"\"");}
try { 
  QFileInfo f2( fileName );
  QString name=f2.baseName();
  QFile f( fileName );
  if ( !f.open( QIODevice::ReadOnly ) )
	throw QString(tr("Can not open File."));
  cellList *firstcellhelp=d->firstCell;
  d->firstCell=NULL;
  df=d;
  d->currentCell=d->addCell()->thisCell;
  d->currentCell->cellName=name;
  QTextStream stream(&f);
  int count=0;
  pointArray pa;
  QTime timer;
  timer.start();
  while (!stream.atEnd()){
	QStringList sl=stream.readLine().split(setup::csvFieldDelimiter);
	if ((sl.size()>1)&&(sl[0].size()>0)&&(sl[1].size()>0)){
		QPoint p=QPoint(element::runden(1.0/df->userunits*sl[0].toDouble()), element::runden(1.0/df->userunits*sl[1].toDouble()));
		pa<<p;
		count++;
	} else if ((sl.size()>=1)&&(sl[0].size()>0)){
		//printf("%s\n",sl[0].toAscii().data());
		int n=sl[0].toInt();
		if ((n>=0)&&(n<layersMax)) d->activeLayer=n;
	}
	else if (pa.size()>0){
		if (pa.point(0)==pa.point(pa.size()-1)){
			d->currentCell->addPolygon(pa,d->activeLayer);
		} else {
			d->currentCell->addPath(pa,d->activeLayer);
		}
		pa.resize(0);
	}
	if ((timer.elapsed()>200)){
	d->showMessage(tr("%1 points converted.").arg(count));
	timer.start();
		}
  }
  f.close();
  if (pa.size()>0){
		if (pa.point(0)==pa.point(pa.size()-1)){
			d->currentCell->addPolygon(pa,d->activeLayer);
		} else {
			d->currentCell->addPath(pa,d->activeLayer);
		}
  }
  d->showMessage(tr("%1 points converted.").arg(count));
  if (typ==fileImport) filegeneral::import(&report,d,firstcellhelp);
  if (typ==fileUpdate) filegeneral::update(&report,d,firstcellhelp);

  }
catch (QString s){
  report.addItem(tr("Aborted. "),0);
  report.addItem(s,1);
 }
  //report.showReport(); 
  QString s=report.getReport();
  d->showReport(s,report.getLastRang());
//printf("3\n");
}

void csv::save(QString fileName,drawingField *d){
errorreport report;
report.setTitle(tr("Save of CSV-File \"")+fileName+"\"");
try { 
  QFile f( fileName );
  if ( !f.open( QIODevice::WriteOnly ) ) {
	throw QString(tr("Can not open File."));
  }
 
  QTextStream stream( &f );
  csv csvClass;
  csvClass.save(&stream,d,&report);
  f.close();
}
catch (QString s){
  report.addItem(tr("Aborted. "),0);
  report.addItem(s,1);
 }
  //report.showReport();   
  QString s=report.getReport();
  d->showReport(s,report.getLastRang());
}

void csv::save(QTextStream *streamPtr,drawingField *d, errorreport *error){
  
  stream = streamPtr;
  error->addItem(tr("Only selected path and polygon elements in the current cell will be saved."),3);
  df=d;
  df->currentCell->saveCSV(this);
}

void csv::savePointArray(pointArray pa){
for (int i=0;i<pa.size();i++){
	saveNum(((double)(pa.point(i).x()))*df->userunits);
	*stream<<setup::csvFieldDelimiter;
	saveNum(((double)(pa.point(i).y()))*df->userunits);
	*stream<<"\r\n";
}
*stream<<setup::csvFieldDelimiter<<"\r\n";
}

void csv::saveNum(double i){
	QString s;
	s.setNum(i,'f',6);
	if (s.contains("."))
		while (s[s.size()-1]=='0') {
			s=s.left(s.size()-1);
		}
	while (s[s.size()-1]=='.') {
		s=s.left(s.size()-1);
	}
	*stream<<s;
}
