/* -*- C++ -*-
   This file implements the method to open a file..

   the KDE addressbook

   $ Author: Mirko Boehm $
   $ Copyright: (C) 1996-2000, Mirko Boehm $
   $ Contact: mirko@kde.org
         http://www.kde.org $
   $ License: GPL with the following explicit clarification:
         This code may be linked against any version of the Qt toolkit
         from Troll Tech, Norway. $

   $Revision: 1.17 $	
*/

#include <kabapi.h>
#include "kab_topwidget.h"
#include <qstring.h>
#include <qfileinfo.h>
#include <qdir.h>
#include <kapp.h>
#include <kmessagebox.h>
#include <knotifyclient.h>
#include <kfiledialog.h>
#include <klocale.h>
#include <kurl.h>
#include <kdebug.h>

void TopLevelWidget::loadDatabaseFile()
{
  register bool GUARD; GUARD=true;
  // ###########################################################################
  kdDebug() << "KabMainWindow::open: called.";
  QString home, filename;
  KURL dummy;
  QFileInfo info;
  // ----- select the filename:
  home=QDir::homeDirPath();
  if(home.isEmpty())
    {
      KMessageBox::sorry
	(this, i18n("Could not find the users home directory."), i18n("Sorry"));
      setStatus(i18n("Intern error!"));
      KNotifyClient::beep(i18n("Could not find the users home directory"));
      return;
    }
  for(;;) // do forever
    {
      dummy = KFileDialog::getOpenURL(home, "*kab", this);
      if(dummy.isEmpty()) // dialog has been cancelled
	{
	  setStatus(i18n("Cancelled."));
	  KNotifyClient::beep();
	  return;
	}
      // WORK_TO_DO: download the URL or find the local file name in filename
      if(!dummy.isLocalFile())
      {
        setStatus(i18n("Only local files supported yet."));
	KNotifyClient::beep();
        return;
      } else {
	filename=dummy.path();
      }
      // ...
      // -----
      info.setFile(filename);
      if(info.isDir() || !info.exists())
	{
	  KMessageBox::sorry
	    (this, i18n("The file does not exist or is a directory.\n"
			"Use \"Create new database...\" to create a new one.\n"
			"Select an existing file to load it."),
	     i18n("File error"));
	} else {
	  kdDebug() << "KabMainWindow::newFile: filename is " <<
		     filename << endl;
	  break;
	}
    }
  // ----- load the file:
  if(api->addressbook()->load(filename)!=AddressBook::NoError)
    {
      KMessageBox::sorry
	(this, i18n("The file could not be loaded."),
	 i18n("File error"));
      KNotifyClient::beep();
      return;
    }
  // -----
  modified=false;
  updateGUI();
  kdDebug() << "KabMainWindow::newFile: done.";
  // ###########################################################################
}

