/* This file is part of the KDE project
 *
 * Copyright (C) 2001 Fernando Llobregat <fernando.llobregat@free.fr>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public License
 * along with this library; see the file COPYING.LIB.  If not, write to
 * the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
 * Boston, MA 02111-1307, USA.
 */ 


/************EXAMPLE OF USING KCARDFACTORY AND KCARDIMPLEMENTATION*******************/
//   QString slott =_kcardchooser->_comboSlots->currentText();
//   KCardGsmImplementation * poi =(KCardGsmImplementation *) KCardFactory::self()->getCard(slott);
  
//   if (!poi) {
//     KMessageBox::sorry(this,i18n("Error retrieving impl"));
//     return; }

  

  
//   if (poi->selectFile("3F00")){
//     KMessageBox::sorry(this,poi->lastErrorMessage());
//     return;
//   }
  
//   if (poi->selectFile("7F20")){
//     KMessageBox::sorry(this,poi->lastErrorMessage());
//     return;
//   }
//   if (poi->selectFile("6F05")){
//     KMessageBox::sorry(this,poi->lastErrorMessage());
//     return;
//   }
//   QString data;
//     if (poi->readTransparentFile(data)){
//       KMessageBox::sorry(this,
// 			 poi->lastErrorMessage());
//       return;
//     }
//   kdDebug() << "Data 6F05:" << data << endl;

//   delete poi;
/****************************************************/


#include "kcardchoosermain.h"
#include "kcardchoosermain.moc"
#include <qlabel.h>
#include <qstringlist.h>
#include <qcombobox.h>
#include <kmessagebox.h>
#include <klocale.h>
#include <kapplication.h>
#include <dcopclient.h>
#include <kconfig.h>
#include <kcarddb.h>
#include <kcardfactory.h>
#include <kcardimplementation.h>
#include <kcardchooser.h>
#include <kdebug.h>

KCardChooserMain::KCardChooserMain(QWidget *parent):
  KDialogBase(parent,
	      parent->caption().latin1(),
	      false,
	      parent->caption(),	      
	      Ok|Cancel)
{

  
  _kcardchooser= new KCardChooser (this);
  setMainWidget(_kcardchooser);
  enableButtonOK(TRUE);
  connect (this,SIGNAL(finished()),kapp,SLOT(quit()));
  connect (_kcardchooser->_comboSlots,SIGNAL(activated(const QString &)),
	   this,SLOT(slotSelected(const QString &)));
  loadCardServices();
  loadSlots();
  
  
}

KCardChooserMain::~KCardChooserMain(){

 

 KConfig config("ksmartcardrc", false, false);

 if (!config.readBoolEntry("Enable Support", false)){

  QByteArray data, retval;
  QCString rettype;
  QDataStream arg(data, IO_WriteOnly);
  QCString modName = "kardsvc";
  arg << modName;
  kapp->dcopClient()->call("kded", "kded", "unloadModule(QCString)", 
			   data, rettype, retval);

 }
  
}

void KCardChooserMain::slotSelected(const QString &slot){

  KCardDB cardDB;
  QString module=QString::null;
  QString cardATR=QString::null;
  QByteArray  retval;
  QCString rettype;
  QByteArray dataATR;
  int atrMatch=-1;



  QDataStream argATR(dataATR,IO_WriteOnly);
  argATR << slot;

  enableButtonOK(TRUE);
  
  if (!kapp->dcopClient()->call("kded", "kardsvc", "getCardATR(QString)", 
			       dataATR, rettype, retval)){
    
    setATR(i18n("No ATR found. DCOP Error."));
    _kcardchooser->_managerLabel->setText(i18n("None"));
    enableButtonOK(FALSE);
    return;
  }
  else {
    
    QDataStream _retReaderATR(retval, IO_ReadOnly);
    _retReaderATR>>cardATR;
    module=cardDB.getModuleName(cardATR);    
    
  }

  if (cardATR.isNull() || module.isNull()){

    enableButtonOK(FALSE);
  }

  KCardImplementation * cardImpl =KCardFactory::self()->getCard(slot,cardATR);

  if (cardImpl!=NULL){
    atrMatch= cardImpl->matchATR(KPCSC::encodeCommand(cardATR));
  }
  else{
    atrMatch=-1;
  }
  setATR((cardATR.isNull())?i18n("No card inserted"):cardATR);
  _kcardchooser->_managerLabel->setText((module.isNull())?i18n("None"):module);
  _kcardchooser->_atrMatchLabel->setText((atrMatch==-1)?i18n("None"):QString("%1 %").arg(atrMatch));

  
  
}


void KCardChooserMain::slotOk(){
 
  
  
  if (_kcardchooser->_comboSlots->currentText()==QString::null){
    KMessageBox::sorry (this,i18n("No slot selected."));
    return;
  }
  
  if (_kcardchooser->_atrLabel->text()==QString::null){
    KMessageBox::sorry (this,i18n("No card ATR detected in %1.").arg(kcardchooser->_comboSlots->currentText()));
    return;
  }

  if (_kcardchooser->_cardList->currentText()==QString::null){
    KMessageBox::sorry (this,i18n("Please select an available card implementation."));
    return;
  }
  KCardDB cardDB;
  if (cardDB.addHandler(_kcardchooser->_atrLabel->text(),
			  _kcardchooser->_cardList->currentText())){

    KMessageBox::error (this,i18n("Error accessing card database. Check 'ksmartcarddb' file."));
  }
   KDialogBase::slotOk();
}

void KCardChooserMain::setATR(const QString & atr){
  _kcardchooser->_atrLabel->setText(atr);
  
}
void KCardChooserMain::setSlot(const QString & slot){

  if (slot==QString::null) return;
  if (_slotList.contains(slot)) {
    
    _kcardchooser->_comboSlots->setCurrentText(slot);
    slotSelected(slot);
    return;
    
  }
  
  KMessageBox::error (this,i18n("Slot '%1' not found in available slots.").arg(slot));
  
}

void KCardChooserMain::loadCardServices(){

 QStringList serv = KCardFactory::self()->getImplementationList();
 _kcardchooser->_cardList->insertStringList(serv);
}


void KCardChooserMain::loadSlots(){

  QByteArray data, retval;
  QCString rettype;
  QDataStream arg(data, IO_WriteOnly);
  QCString modName = "kardsvc";
  arg << modName;

  enableButtonOK(TRUE);
  if (!kapp->dcopClient()->call("kded", "kardsvc", "getSlotList ()", 
				data, rettype, retval)){
    
    _kcardchooser->_comboSlots->insertItem(i18n("No readers found. DCOP Error"));
    _kcardchooser->_comboSlots->setEnabled(FALSE);
    enableButtonOK(FALSE);
    return;

 }
  
  _slotList.clear();
  QDataStream _retReader(retval, IO_ReadOnly);
  _retReader>>_slotList;
  
  
  _kcardchooser->_comboSlots->clear();
  
  if (_slotList.isEmpty()){
    _kcardchooser->_comboSlots->insertItem(i18n("No readers found"));
    _kcardchooser->_comboSlots->setEnabled(FALSE);
    enableButtonOK(FALSE);
    return;
  }
  
  _kcardchooser->_comboSlots->insertStringList(_slotList);
}


