/***************************************************************************
                          listexportdialog.cpp -  description
                             -------------------
    begin                : Tue Sep 09 2008
    copyright            : (C) 2008 by Antonio Nastasi
    email                : sifcenter@gmail.com
 ***************************************************************************/

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

#include "../contact/contact.h"
#include "../model/contactlist.h"
#include "../utils/kmessshared.h"
#include "../currentaccount.h"
#include "../kmessdebug.h"

#include <QFileDialog>
#include <KMessageBox>

#include <KIcon>


ListExportDialog::ListExportDialog( QWidget *parent )
  :  QWidget( parent )
{
  setObjectName( "ListExport" );
  setupUi( this );

  // Connect the signal and set the icons for the buttons
  connect( exportButton_,      SIGNAL( clicked() ), this, SLOT( slotExport()      ) );
  connect( closeButton_,       SIGNAL( clicked() ), this, SLOT( hide()            ) );
  connect( selectAllButton_,   SIGNAL( clicked() ), this, SLOT( slotSelectAll()   ) );
  connect( deselectAllButton_, SIGNAL( clicked() ), this, SLOT( slotDeselectAll() ) );

  exportButton_->setIcon( KIcon( "document-export" ) );
  closeButton_ ->setIcon( KIcon( "dialog-close" ) );

  setupWidgets();
}



ListExportDialog::~ListExportDialog()
{
  kDebug() << "DESTROYED";
}



// Returns the string formatted in csv
QString ListExportDialog::getCsvString( const QString &text )
{
  QString csvFormatted( text );
  // Replace the " with ""
  csvFormatted.replace( "\"", "\"\"" );

  // If text contains "," char, use the " chars
  if( csvFormatted.contains( "," ) )
  {
    csvFormatted = "\"" + csvFormatted + "\"";
  }

  return csvFormatted;
}



// Setup the widgets
void ListExportDialog::setupWidgets()
{
  QListWidgetItem *currentItem;
  CurrentAccount *currentAccount = CurrentAccount::instance();

  setWindowTitle( i18n( "Export Contact List for %1", currentAccount->getHandle() ) );
  csvButton_->setChecked( true );

  // Fill the exportable items list
  QStringList exportableItems;
  exportableItems << "Handle" << "Friendly Name" << "Current PM";
  foreach( const QString &item, exportableItems )
  {
    currentItem = new QListWidgetItem( item, itemsListWidget_ );
    currentItem->setFlags( Qt::ItemIsUserCheckable | Qt::ItemIsEnabled );
    currentItem->setCheckState( Qt::Checked );
  }

  // Grep the current contact list
  QHash<QString,Contact*> contacts = currentAccount->getContactList()->getContactList();

  // If the list is empty, disable the export button and notify this to user
  if( contacts.size() == 0 )
  {
    currentItem = new QListWidgetItem( i18n( "Nothing to export" ), contactListWidget_ );

    selectAllButton_  ->setEnabled( false );
    deselectAllButton_->setEnabled( false );
    exportButton_     ->setEnabled( false );
    return;
  }

  // Catch all contacts in the contact list of current account and put it in the list widget
  QHashIterator<QString,Contact*> i( contacts );
  Contact *contact;

  while( i.hasNext() )
  {
    i.next();
    contact = i.value();

    // Use the checkable style
    currentItem = new QListWidgetItem( contact->getHandle(), contactListWidget_ );
    currentItem->setFlags( Qt::ItemIsUserCheckable | Qt::ItemIsEnabled );
    currentItem->setCheckState( Qt::Checked );
  }
}



// The export button was pressed
void ListExportDialog::slotExport()
{
  // Use the file dialog to determinate the file name
  QString fileName( QFileDialog::getSaveFileName( this ) );

  // Check if the filename is empty
  if( fileName.isEmpty() )
  {
    return;
  }

  // Check if the file has the extension and add one if there isn't.
  QFileInfo fileInfo( fileName );
  if( fileInfo.suffix().isEmpty() )
  {
    if( csvButton_->isChecked() )
    {
      fileName += ".csv";
    }
    else if( xmlButton_->isChecked() )
    {
      fileName += ".xml";
    }
  }

  // Check if the file already exists
  QFile file( fileName );
  if( file.exists() )
  {
    if( KMessageBox::questionYesNo( this, i18n( "The file %1 already exists, do you want to overwrite?", fileName ), i18n( "File exists" ) ) == KMessageBox::No )
    {
      return;
    }
  }

  // Open the file for the writing
  if( ! file.open( QIODevice::WriteOnly | QIODevice::Text ) )
  {
    return;
  }

  QTextStream out( &file );

  // Get all items and save in select format
  QListWidgetItem *currentContact;
  Contact *contact;
  bool isCsv = csvButton_->isChecked();
  QString text;

  if( ! isCsv )
  {
      // XML format was selected
    out << "<contactlist>\n";
  }

  for( int i = 0; i < contactListWidget_->count(); i++ )
  {
    // Check which contacts the user wants to export
    currentContact = contactListWidget_->item( i );
    if( currentContact->checkState() != Qt::Checked )
    {
      continue;
    }

    if( ! isCsv )
    {
      // XML format was selected
      out << "\t<contact>\n";
    }

    // Check which items the user wants to save
    // Handle
    if( itemsListWidget_->item( 0 )->checkState() == Qt::Checked )
    {
      // CSV
      if( isCsv )
      {
        out << getCsvString( currentContact->text() );
      }
      else
      {
        out << "\t\t<handle>" + currentContact->text() + "</handle>\n";
      }
    }

    // Friendly name
    if( itemsListWidget_->item( 1 )->checkState() == Qt::Checked )
    {
      contact = CurrentAccount::instance()->getContactList()->getContactByHandle( currentContact->text() );
      if( contact != NULL )
      {
        // CSV
        if( isCsv )
        {
          out << "," << getCsvString( contact->getFriendlyName() );
        }
        else
        {
          text = contact->getFriendlyName( STRING_ORIGINAL );
          out << "\t\t<friendlyname>" + KMessShared::htmlEscape( text )
                  + "</friendlyname>\n";
        }
      }
    }

    // Personal Message
    if( itemsListWidget_->item( 2 )->checkState() == Qt::Checked )
    {
      contact = CurrentAccount::instance()->getContactList()->getContactByHandle( currentContact->text() );
      if( contact != NULL )
      {
        // CSV
        if( isCsv )
        {
          out << "," << getCsvString( contact->getPersonalMessage( STRING_ORIGINAL ) );
        }
        else
        {
          text = contact->getPersonalMessage( STRING_ORIGINAL );
          out << "\t\t<personalMessage>" + KMessShared::htmlEscape( text )
                 + "</personalMessage>\n";
        }
      }
    }

    if( isCsv )
    {
      out << "\n";
    }
    else
    {
      out << "\t</contact>\n";
    }
  }

  if( ! isCsv )
  {
    // XML format was selected
    out << "</contactlist>";
  }

  KMessageBox::information( this, i18n( "Export Finished" ), i18n( "The export of the contact list is finished" ) );
  file.close();
  hide();
}



// Select or deselect the items of the contact list
void ListExportDialog::selectAll( bool select )
{
  QListWidgetItem *currentContact;
  for( int i = 0; i < contactListWidget_->count(); i++ )
  {
    // Select or deselect item
    currentContact = contactListWidget_->item( i );
    currentContact->setCheckState( select ? Qt::Checked : Qt::Unchecked );
  }
}



// The deselect all button was pressed
void ListExportDialog::slotDeselectAll()
{
  selectAll( false );
}



// The select all button was pressed
void ListExportDialog::slotSelectAll()
{
  selectAll();
}

#include "listexportdialog.moc"
