#include <stdlib.h>
#include <stdio.h>

#include "kapplication.h"
#include <qapplication.h>
#include <qstring.h>
#include <qfile.h>
#include <qtextstream.h>
#include <qdialog.h>
#include <qlayout.h>
#include <qtextbrowser.h>

int KApplication::random()
{
  return rand();
}

//US
QString KApplication::randomString(int length)
{
   if (length <=0 ) return QString::null;

   QString str;
   while (length--)
   {
      int r=random() % 62;
      r+=48;
      if (r>57) r+=7;
      if (r>90) r+=6;
      str += char(r);
      // so what if I work backwards?
   }
   return str;
}
int KApplication::execDialog( QDialog* d )
{
    if (QApplication::desktop()->width() <= 640 )    
        d->showMaximized();
    return d->exec();
}
void KApplication::showLicence()
{
   KApplication::showFile( "KDE-Pim/Pi licence", "kdepim/LICENCE.TXT" );
}

void KApplication::showFile(QString caption, QString fn)
{
    QString text;
    QString fileName;
#ifndef DESKTOP_VERSION
   fileName = getenv("QPEDIR");
   fileName += "/pics/" + fn ;
#else
   fileName  = qApp->applicationDirPath () + "/" + fn;
#endif 
    QFile file( fileName );
    if (!file.open( IO_ReadOnly ) ) {
        return ;
    } 
    QTextStream ts( &file );
    text = ts.read();
    file.close();
    KApplication::showText( caption, text );
  
}
 
bool KApplication::convert2latin1(QString fileName)
{
    QString text;
    QFile file( fileName );
    if (!file.open( IO_ReadOnly ) ) {
        return false;
        
    } 
    QTextStream ts( &file );
    ts.setEncoding( QTextStream::UnicodeUTF8 );
    text = ts.read();
    file.close();  
    if (!file.open( IO_WriteOnly ) ) {
        return false;
    }
    QTextStream tsIn( &file );
    tsIn.setEncoding( QTextStream::Latin1 );
    tsIn << text.latin1();
    file.close();  
 

}
void KApplication::showText(QString caption, QString text)
{
    QDialog dia( 0, "name", true ); ;
    dia.setCaption( caption );
    QVBoxLayout* lay = new QVBoxLayout( &dia );
    lay->setSpacing( 3 );
    lay->setMargin( 3 );
    QTextBrowser tb ( &dia );
    lay->addWidget( &tb ); 
    tb.setText( text );
#ifdef DESKTOP_VERSION
    dia.resize( 640, 480);
#else
    dia.showMaximized();
#endif
    dia.exec();

}