/***************************************************************************
                          qcakedoc.cpp  -  description
                             -------------------
    begin                : Sun Nov  7 16:54:22 CET 2004
    copyright            : (C) 2004 by Harald Krippel
    email                : neuro.harald@surfeu.at
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 files for Qt
#include <qdir.h>
#include <qfileinfo.h>
#include <qwidget.h>
#include <qmessagebox.h>
#include <qfiledialog.h>


// application specific includes
#include "qcakedoc.h"
#include "qcake.h"
#include "kcakeview.h"
#include "myprojectdlg.h"
#include "copydir.h"

QcakeDoc::QcakeDoc(QWidget *parent, const char *name) : QObject(parent, name)
{
      modified = false;
//  pViewList = new QList<KCakeView>;
//  pViewList->setAutoDelete(false);
}

QcakeDoc::~QcakeDoc()
{
//  delete pViewList;
}

void QcakeDoc::addView(KCakeView *nview)
{
//  pViewList->append(view);
//	changedViewList();
      view = nview;

}

void QcakeDoc::removeView(KCakeView *nview)
{
//	  pViewList->remove(view);
//	  if(!pViewList->isEmpty())
//			changedViewList();
//		else
//			deleteContents();
}

void QcakeDoc::changedViewList(){	
	
//	KCakeView *w;
//	if((int)pViewList->count() == 1){
//  	w=pViewList->first();
//  	w->setCaption(m_title);
//	}
//	else{
//		int i;
//    for( i=1,w=pViewList->first(); w!=0; i++, w=pViewList->next())
//  		w->setCaption(QString(m_title+":%1").arg(i));	
//	}
}

bool QcakeDoc::isLastView() {
//  return ((int) pViewList->count() == 1);
    return 1;
}


void QcakeDoc::updateAllViews(KCakeView *sender)
{

//  KCakeView *w;
//  for(w=pViewList->first(); w!=0; w=pViewList->next())
//  {
//      if(w!=sender)
//        w->repaint();
//  }


      if(view!=sender)
        view->repaint();

}

void QcakeDoc::setPathName(const QString &name)
{
  m_filename=name;
	m_title=QFileInfo(name).fileName();
}

const QString& QcakeDoc::pathName() const
{
  return m_filename;
}

void QcakeDoc::setTitle(const QString &title)
{
  m_title=title;
}

const QString &QcakeDoc::title() const
{
  return m_title;
}


void QcakeDoc::closeDocument()
{

  deleteContents();

//  KCakeView *w;
//  if(!isLastView())
//  {
//    for(w=pViewList->first(); w!=0; w=pViewList->next())
//    {
//   	 	if(!w->close())
// 				break;
//    }
//	}
//  if(isLastView())
//  {
//  	w=pViewList->first();
//  	w->close();
//  }
}

bool QcakeDoc::newDocument()
{
  /////////////////////////////////////////////////
  // TODO: Add your document initialization code here
  /////////////////////////////////////////////////
  modified=false;

  QString copy;

  MyProjectEditDlg  *project = new  MyProjectEditDlg();
  if ( project->exec() == QDialog::Accepted )
  {
         QString   result = project->getfile();
         QString   workingDirectory = project->getpath();
         qWarning( result );
         qWarning( workingDirectory );
         QDir *dir =new QDir();
         dir->mkdir(workingDirectory);
         g_prjpath =  workingDirectory + "/";

         // copy the data folder
#ifdef    Q_OS_LINUX
         QString   copy = "cp -dpR data " +  g_prjpath ;
         qWarning( "%s",copy.latin1() );
         system (copy.latin1());
#endif

#ifdef    Q_OS_MACX
         QString   copy = "cp -pR " + workingDirectory + result + ' ' +  g_prjpath + "data/";
         qWarning( "%s",copy.latin1() );
         system (copy.latin1());
#endif

#ifdef    Q_OS_WIN32
         copydir mycopy;
         mycopy.copy("data",g_prjpath + "data/");
#endif

         copy = "cp new.xml " +  g_prjpath + result + ".xml";
         qWarning( "%s",copy.latin1() );


         // copy new.xml
         #define BUFFER_SIZE  1024

         Q_INT8 buffer[BUFFER_SIZE];


         QFile srcFile("new.xml");
         if ( !srcFile.open( IO_ReadOnly ) )
         {
              qWarning( "can not open srcFile !!" );
              return false;
         }
         QFile destFile(g_prjpath + result + ".xml");
         if ( !destFile.open( IO_Raw | IO_ReadWrite ) )
         {
              qWarning( "can not open destFile !!" );
              srcFile.close();
              return false;
         }         
         QDataStream srcStream(&srcFile);
         QDataStream destStream(&destFile);

          while(!srcStream.atEnd())
          {
	          int i = 0;
	          while(!srcStream.atEnd() && i < BUFFER_SIZE)
	          {
		          srcStream >> buffer[i];
		          i++;
	          }
	          for(int k = 0; k < i; k++)
	          {
		          destStream << buffer[k];
	          }
          }
          srcFile.close();
          destFile.close();

         // open project xxx.xml file
         QString  myurl = g_prjpath + result + ".xml";
         openDocument(myurl);
         doc_url = g_prjpath + result + ".xml" ;         
  }
  else
  {
    return false;
  }

  return true;
}

bool QcakeDoc::openDocument(const QString &filename, const char *format /*=0*/)
{


  QDomDocument domdoc("mydocument");
  
	QFile f( filename );

  if ( !f.open( IO_ReadOnly ) )
  {
    qWarning( "can not open File !!" );
		return false;
  }
  if ( !domdoc.setContent( &f ) ) {
    qWarning( "can not open DomDoc !!" );
    f.close();
    return false;
  }

  f.close();

  	
  g_prjpath =  QFileInfo(f).filePath();
  g_prjpath = g_prjpath.left(g_prjpath.findRev(QFileInfo(f).fileName()));
  qWarning( "%s",g_prjpath.latin1() );
  modified=false;
  m_filename=filename;
	m_title=QFileInfo(f).fileName();

  view->doc= this;
  view->initListView(&domdoc,g_prjpath);

  return true;
}

bool QcakeDoc::saveDocument(const QString &filename, const char *format /*=0*/)
{
  QDomDocument sdomdoc;

  view->getListView(&sdomdoc);

    QFile file(filename );
    if ( file.open( IO_WriteOnly ) )
    {
      QTextStream stream( &file );
      stream << sdomdoc.toString();
      file.close();
    }
  
  modified=false;
  m_filename=filename;
	m_title=QFileInfo(file).fileName();
  return true;
}

void QcakeDoc::deleteContents()
{
  /////////////////////////////////////////////////
  // TODO: Add implementation to delete the document contents
  /////////////////////////////////////////////////

}

bool QcakeDoc::canCloseFrame(KCakeView* pFrame)
{
	if(!isLastView())
		return true;
		
	bool ret=false;
  if(isModified())
  {
		QString saveName;
  	switch(QMessageBox::information(pFrame, title(), tr("The current file has been modified.\n"
                          "Do you want to save it?"),QMessageBox::Yes, QMessageBox::No, QMessageBox::Cancel ))
    {
			case QMessageBox::Yes:
				if(title().contains(tr("Untitled")))
				{
					saveName=QFileDialog::getSaveFileName(0, 0, pFrame);
                                          if(saveName.isEmpty())
          	                                return false;
				}
				else
					saveName=pathName();

				if(!saveDocument(saveName))
				{
 					switch(QMessageBox::critical(pFrame, tr("I/O Error !"), tr("Could not save the current document !\n"
																												"Close anyway ?"),QMessageBox::Yes ,QMessageBox::No))

 					{
 						case QMessageBox::Yes:
 							ret=true;
 						case QMessageBox::No:
 							ret=false;
 					}
				}
				else
					ret=true;
				break;
			case QMessageBox::No:
				ret=true;
				break;
			case QMessageBox::Cancel:
			default:
				ret=false;
				break;
		}
	}
	else
		ret=true;

	return ret;
}

void QcakeDoc::setURL(const QString &url)
{
  doc_url=url;
}
const QString& QcakeDoc::URL() const
{
  return doc_url;
}
