/***************************************************************************
                          kdrawchemdoc.cpp  -  description
                             -------------------
    begin                : Mon Jul 15 12:24:12 CDT 2002
    copyright            : (C) 2002 by Adam Tenderholt
    email                : a-tenderholt@northwestern.edu
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   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 <qwidget.h>

// include files for KDE
#include <klocale.h>
#include <kmessagebox.h>
#include <kio/job.h>
#include <kio/netaccess.h>

// application specific includes
#include "kdrawchemdoc.h"
#include "kdrawchem.h"
#include "kdrawchemview.h"
#include <mol.h>


QList<KDrawChemView> *KDrawChemDoc::pViewList = 0L;

KDrawChemDoc::KDrawChemDoc(QWidget *parent, const char *name) : ChemData(parent, name)
{
  if(!pViewList)
  {
    pViewList = new QList<KDrawChemView>();
  }

  pViewList->setAutoDelete(true);
}

KDrawChemDoc::~KDrawChemDoc()
{
}

void KDrawChemDoc::addView(KDrawChemView *view)
{
  pViewList->append(view);
  view->setChemData(dynamic_cast<ChemData*>(this));
  this->setRender2D(dynamic_cast<Render2D*>(view));
}

void KDrawChemDoc::removeView(KDrawChemView *view)
{
  pViewList->remove(view);
}
void KDrawChemDoc::setURL(const KURL &url)
{
  doc_url=url;
}

const KURL& KDrawChemDoc::URL() const
{
  return doc_url;
}

void KDrawChemDoc::slotUpdateAllViews(KDrawChemView *sender)
{
  KDrawChemView *w;
  if(pViewList)
  {
    for(w=pViewList->first(); w!=0; w=pViewList->next())
    {
      if(w!=sender)
        w->repaint();
    }
  }

}

bool KDrawChemDoc::saveModified()
{
  bool completed=true;

  if(modified)
  {
    KDrawChemApp *win=(KDrawChemApp *) parent();
    int want_save = KMessageBox::warningYesNoCancel(win,
                                         i18n("The current file has been modified.\n"
                                              "Do you want to save it?"),
                                         i18n("Warning"));
    switch(want_save)
    {
      case KMessageBox::Yes:
           if (doc_url.fileName() == i18n("Untitled"))
           {
             win->slotFileSaveAs();
           }
           else
           {
             saveDocument(URL());
       	   };

       	   deleteContents();
           completed=true;
           break;

      case KMessageBox::No:
           setModified(false);
           deleteContents();
           completed=true;
           break;

      case KMessageBox::Cancel:
           completed=false;
           break;

      default:
           completed=false;
           break;
    }
  }

  return completed;
}

void KDrawChemDoc::closeDocument()
{
  deleteContents();
}

bool KDrawChemDoc::newDocument()
{
  /////////////////////////////////////////////////
  // TODO: Add your document initialization code here
  /////////////////////////////////////////////////
  modified=false;
  doc_url.setFileName(i18n("Untitled"));


  /*KDrawChemView* _view=parent->getView();
  if(_view) {

    doc->removeView(_view);
    delete view;
    _view=new KDrawChemView(parent);
    parent->setCentralWidget(_view);
    doc->addView(_view);
    parent->setCaption(doc->URL().fileName(),false);
    connect(_view,SIGNAL(signalModified()),doc,SLOT(slotModified()));
    connect(_view,SIGNAL(signalModified()),this,SLOT(slotModified()));
    */
  return true;
}

bool KDrawChemDoc::openDocument(const KURL& url, const char *format /*=0*/)
{
  QString tmpfile;
  KIO::NetAccess::download( url, tmpfile );

  doc_url=url;
  bool returnFlag;
  returnFlag=dynamic_cast<ChemData*>(this)->load(tmpfile);
  KIO::NetAccess::removeTempFile( tmpfile );

  modified=false;
  return returnFlag;
}

bool KDrawChemDoc::import(const KURL& url, const char* format /*=0*/) {

    QString tmpfile("kdctemp");

    QString filename=url.fileName();
    tmpfile.append(filename.right(3));

    KIO::NetAccess::download(url,tmpfile);
    OBMol *mol=new OBMol;

    OBExtensionTable extab;
	  enum io_type importType;

	  importType=extab.FilenameToType(const_cast<char*>(tmpfile.latin1()));  //doesn't like being a const char*--casted it to a char*

	  mol->SetInputType(importType);
	  std::fstream fin(tmpfile,std::ios::in);
	  if(fin==NULL) {
      std::cerr << "Somethign wrong" << std::endl;
	    return false;
    }

	    //fin >> mol;  Old school code from OELib--now use OpenBabel code;
	  OBFileFormat file;
	  file.ReadMolecule(fin,*mol);

    KDrawChemApp::interface.setChemData(dynamic_cast<ChemData*>(this));
    KDrawChemApp::interface.setOBMol(mol);
    KDrawChemApp::interface.convertToChemData();

    KIO::NetAccess::removeTempFile(tmpfile);
    modified=false;
}


bool KDrawChemDoc::saveDocument(const KURL& url, const char *format /*=0*/)
{
  /////////////////////////////////////////////////
  // TODO: Add your document saving code here
  /////////////////////////////////////////////////
	bool returnFlag;
	returnFlag=dynamic_cast<ChemData*>(this)->save(url.path(-1));
  std::cerr << url.path(-1).latin1() << std::endl;
  if(returnFlag)
    setURL(url);
  else
    std::cerr << "in KDrawChem::saveDocument(), returnFlag is false" << std::endl;
  modified=false;
  return returnFlag;
}

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

}
/** Sets the modified flag to true */
void KDrawChemDoc::slotModified(){
  modified=true;
}
/** No descriptions */
void KDrawChemDoc::slotFilterChanged(const QString& filter){
  myFilter=filter;
  std::cerr << "in slotFilterChanged " << myFilter.latin1() << std::endl;
}


#include "kdrawchemdoc.moc"