#include "composemail.h"

#include <libmailwrapper/smtpwrapper.h>
#include <libmailwrapper/storemail.h>
#include <libmailwrapper/abstractmail.h>
#include <libmailwrapper/mailtypes.h>

/* OPIE */
//#include <opie2/ofiledialog.h>
//#include <opie2/odebug.h>
#include <kfiledialog.h>
//#include <qpe/resource.h>
#include <qpe/config.h>
#include <qpe/global.h>
//#include <qpe/contact.h>


#include <qcombobox.h>
#include <qcheckbox.h>
#include <qtimer.h>
#include <qmessagebox.h>
#include <qpushbutton.h>
#include <qmultilineedit.h>
#include <qlabel.h>
#include <qtabwidget.h>
#include <qlistview.h>
#include <kabc/addresseedialog.h>
#include <kabc/stdaddressbook.h>
#include <kabc/addressee.h>



//using namespace Opie::Core;
//using namespace Opie::Ui;
ComposeMail::ComposeMail( Settings *s, QWidget *parent, const char *name, bool modal, WFlags flags )
    : ComposeMailUI( parent, name, modal, flags )
{
   
    settings = s;
    m_replyid = "";
    KABC::Addressee con =  KABC::StdAddressBook::self()->whoAmI( );
    QStringList mails = con.emails();
    QString defmail = con.preferredEmail();
    if (  mails.count() == 0)
         QMessageBox::information( 0, tr( "Hint" ),
                                  tr( "Please apply\n\"Set Who Am I\"\nin KA/Pi to get the from\nfield automatically filled out!\n" ),
                                  tr( "Ok" ) );
    if (defmail.length()!=0) {
        fromBox->insertItem(defmail);
    }
    QStringList::ConstIterator sit = mails.begin();
    for (;sit!=mails.end();++sit) {
        if ( (*sit)==defmail)
            continue;
        fromBox->insertItem((*sit));
    }
    senderNameEdit->setText(con.formattedName());
    Config cfg( "mail" );
    cfg.setGroup( "Compose" );
    checkBoxLater->setChecked( cfg.readBoolEntry( "sendLater", false ) );

    attList->addColumn( tr( "Name" ) );
    attList->addColumn( tr( "Size" ) );

    QList<Account> accounts = settings->getAccounts();

    Account *it;
    for ( it = accounts.first(); it; it = accounts.next() ) {
        if ( it->getType()==MAILLIB::A_SMTP ) {
           SMTPaccount *smtp = static_cast<SMTPaccount *>(it);
           smtpAccountBox->insertItem( smtp->getAccountName() );
           smtpAccounts.append( smtp );
        }
    }
    if ( smtpAccounts.count() > 0 ) {
        fillValues( smtpAccountBox->currentItem() );
    } else {
        QMessageBox::information( 0, tr( "Problem" ),
                                  tr( "Please create an SMTP account first.\nThe SMTP is needed for sending mail.\n" ),
                                  tr( "Ok" ) );
        return;
    }
    connect( smtpAccountBox, SIGNAL( activated(int) ), SLOT( fillValues(int) ) );
    connect( toButton, SIGNAL( clicked() ), SLOT( pickAddressTo() ) );
    connect( ccButton, SIGNAL( clicked() ), SLOT( pickAddressCC() ) );
    connect( bccButton, SIGNAL( clicked() ), SLOT( pickAddressBCC() ) );
    connect( replyButton, SIGNAL( clicked() ), SLOT( pickAddressReply() ) );
    connect( addButton, SIGNAL( clicked() ), SLOT( addAttachment() ) );
    connect( deleteButton, SIGNAL( clicked() ), SLOT( removeAttachment() ) );
    connect( SaveButton, SIGNAL( clicked() ), SLOT( saveAsDraft()) );
    mMail = 0;
    warnAttach = true;
   
}
void ComposeMail::saveAsDraft()
{
  
    Opie::Core::OSmartPointer<Mail> mail= new Mail();
        mail->setMail(fromBox->currentText());
        mail->setTo( toLine->text() );
        mail->setName(senderNameEdit->text());
        mail->setCC( ccLine->text() );
        mail->setBCC( bccLine->text() );
        mail->setReply( replyLine->text() );
        mail->setSubject( subjectLine->text() );
        if (!m_replyid.isEmpty()) {
            QStringList ids;
            ids.append(m_replyid);
            mail->setInreply(ids);
        }
        QString txt = message->text();
        if ( !sigMultiLine->text().isEmpty() ) {
            txt.append( "\n--\n" );
            txt.append( sigMultiLine->text() );
        }
        mail->setMessage( txt );

        /* only use the default drafts folder name! */
        Storemail wrapper(AbstractMail::draftFolder());
        wrapper.storeMail(mail);

        AttachViewItem *it = (AttachViewItem *) attList->firstChild();
        /* attachments we will ignore! */
        if ( it != 0 ) {
            if ( warnAttach )
            QMessageBox::warning(0,tr("Store message"),
                tr("<center>Attachments will not be stored in \"Draft\" folder</center>"));
            warnAttach = false;
        }
        setStatus( tr("Mail saved as draft!") );
}
void  ComposeMail::clearStatus()
{
    topLevelWidget()->setCaption( tr("Compose mail") );
}
void  ComposeMail::setStatus( QString status )
{
    topLevelWidget()->setCaption( status );
    QTimer::singleShot ( 10000, this, SLOT( clearStatus() ) ) ;
}
void ComposeMail::pickAddress( QLineEdit *line )
{
    //qDebug(" ComposeMail::pickAddress ");
    QString names ;//= AddressPicker::getNames();

    KABC::Addressee::List list = KABC::AddresseeDialog::getAddressees(this);
    uint i=0;
    for (i=0; i < list.count(); i++) {
        if ( !list[i].preferredEmail().isEmpty()) {
            names+=  "\""+list[i].realName() +"\"<" +list[i].preferredEmail() +">";
            if ( i < list.count() -1 )
                names+= ",";
        }
    }


    if ( line->text().isEmpty() ) {
        line->setText( names );
    } else if ( !names.isEmpty() ) {
        line->setText( line->text() + ", " + names );
    }
}


void ComposeMail::setTo( const QString & to )
{
    toLine->setText( to );
}

void ComposeMail::setSubject( const QString & subject )
{
 subjectLine->setText( subject );
}

void ComposeMail::setInReplyTo( const QString & messageId )
{
    m_replyid = messageId;
}

void ComposeMail::setMessage( const QString & text )
{
  message->setText( text );
}


void ComposeMail::pickAddressTo()
{
    pickAddress( toLine );
}

void ComposeMail::pickAddressCC()
{
    pickAddress( ccLine );
}

void ComposeMail::pickAddressBCC()
{
    pickAddress( bccLine );
}

void ComposeMail::pickAddressReply()
{
    pickAddress( replyLine );
}

void ComposeMail::fillValues( int )
{
#if 0
    SMTPaccount *smtp = smtpAccounts.at( current );
    ccLine->clear();
    if ( smtp->getUseCC() ) {
        ccLine->setText( smtp->getCC() );
    }
    bccLine->clear();
    if ( smtp->getUseBCC() ) {
        bccLine->setText( smtp->getBCC() );
    }
    replyLine->clear();
    if ( smtp->getUseReply() ) {
        replyLine->setText( smtp->getReply() );
    }
    sigMultiLine->setText( smtp->getSignature() );
#endif
}

void ComposeMail::slotAdjustColumns()
{
    int currPage = tabWidget->currentPageIndex();

    tabWidget->showPage( attachTab );
    attList->setColumnWidth( 0, attList->visibleWidth() - 80 );
    attList->setColumnWidth( 1, 80 );

    tabWidget->setCurrentPage( currPage );
}

void ComposeMail::addAttachment()
{
    QString lnk = KFileDialog::getOpenFileName( "", "Add Attachment", this );
    if ( !lnk.isEmpty() ) {
        Attachment *att = new Attachment( lnk );
        (void) new AttachViewItem( attList, att );
    }
}

void ComposeMail::removeAttachment()
{
    if ( !attList->currentItem() ) {
        QMessageBox::information( this, tr( "Error" ),
                                  tr( "<p>Please select a File.</p>" ),
                                  tr( "Ok" ) );
    } else {
        attList->takeItem( attList->currentItem() );
    }
}

void ComposeMail::accept()
{
    if ( smtpAccountBox->count() == 0 ) { 
       
        reject();
        return;
    }

    if (! checkBoxLater->isChecked() ) {
        int yesno = QMessageBox::warning(0,tr("Stop editing message"),
                                         tr("Send this message?"),
                                         tr("Yes"),
                                         tr("Cancel"));
        
        if (yesno == 1) {
            return;
        }
    }
#if 0
    odebug << "Sending Mail with "
           << smtpAccounts.at( smtpAccountBox->currentItem() )->getAccountName() << oendl;
#endif
    Opie::Core::OSmartPointer<Mail> mail=new Mail;

    SMTPaccount *smtp = smtpAccounts.at( smtpAccountBox->currentItem() );
    mail->setMail(fromBox->currentText());

    if ( !toLine->text().isEmpty() ) {
        mail->setTo( toLine->text() );
    } else {
        QMessageBox::warning(0,tr("Sending mail"),
            tr("No Receiver spezified" ) );
        return;
    }  
   
    mail->setName(senderNameEdit->text());
    mail->setCC( ccLine->text() );
    mail->setBCC( bccLine->text() );
    mail->setReply( replyLine->text() );
    mail->setSubject( subjectLine->text() );
    if (!m_replyid.isEmpty()) {
        QStringList ids;
        ids.append(m_replyid);
        mail->setInreply(ids);
    }
    QString txt = message->text();
    if ( !sigMultiLine->text().isEmpty() ) {
        txt.append( "\n--\n" );
        txt.append( sigMultiLine->text() );
    }
    mail->setMessage( txt );
    AttachViewItem *it = (AttachViewItem *) attList->firstChild();
    while ( it != 0 ) {
        mail->addAttachment( it->getAttachment() );
        it = (AttachViewItem *) it->nextSibling();
    }

    SMTPwrapper wrapper( smtp );
    if ( wrapper.sendMail( mail,checkBoxLater->isChecked() ) )
        setStatus( tr ("Mail sent"));
    else {
        setStatus( tr ("Error: Something went wrong. Nothing sent"));
        return;
    }
        

    QDialog::accept();
}

void ComposeMail::reject()
{
    //qDebug("ComposeMail::reject() ");
    int yesno = QMessageBox::warning(0,tr("Store message?"),
                                     tr("Store message into drafts?\n"),
                                     tr("Yes"),
                                     tr("No"));

    //qDebug("button %d ", yesno);
    if (yesno == 0) {
        if ( toLine->text().isEmpty() ) {
            QMessageBox::warning(0,tr("Sending mail"),
                                 tr("No Receiver spezified" ) );
            return;
        }  
        saveAsDraft();
    }
    if (yesno == 2) {
        qDebug("return ");
        return;
    }
    QDialog::reject();
}

ComposeMail::~ComposeMail()
{
}

void ComposeMail::reEditMail(const RecMailP&current)
{
    RecMailP data = current;
    message->setText(data->Wrapper()->fetchBody(current)->Bodytext());
    subjectLine->setText( data->getSubject());
    toLine->setText(data->To().join(","));
    ccLine->setText(data->CC().join(","));
    bccLine->setText(data->Bcc().join(","));
    replyLine->setText(data->Replyto());
}

AttachViewItem::AttachViewItem( QListView *parent, Attachment *att )
    : QListViewItem( parent )
{
    attachment = att;
    if ( !attachment->getPixmap().isNull() )
        setPixmap( 0,attachment->getPixmap() );
    setText( 0, att->getName().isEmpty() ? att->getFileName() : att->getName() );
    setText( 1, QString::number( att->getSize() ) );
}