 /*
  This file is or will be part of KDE desktop environment

  Copyright 1999 Matt Koss <koss@miesto.sk>

  It is licensed under GPL version 2.

  If it is part of KDE libraries than this file is licensed under
  LGPL version 2.
 */

import org.trinitydesktop.qt.*;
import org.trinitydesktop.koala.*;
import java.io.ByteArrayOutputStream;

class KioslaveTest  extends TDEMainWindow {

  static final int List = 0;
  static final int ListRecursive = 1;
  static final int Stat = 2;
  static final int Get = 3;
  static final int Put = 4;
  static final int Copy = 5;
  static final int Move = 6;
  static final int Delete = 7;
  static final int Shred = 8;
  static final int Mkdir = 9;
  static final int Mimetype = 10;

  static final int ProgressNone = 0;
  static final int ProgressDefault = 1;
  static final int ProgressStatus = 2;

  // info stuff
  TQLabel lb_from;
  TQLineEdit le_source;

  TQLabel lb_to;
  TQLineEdit le_dest;

  // operation stuff
  TQButtonGroup opButtons;

  TQRadioButton rbList;
  TQRadioButton rbListRecursive;
  TQRadioButton rbStat;
  TQRadioButton rbGet;
  TQRadioButton rbPut;
  TQRadioButton rbCopy;
  TQRadioButton rbMove;
  TQRadioButton rbDelete;
  TQRadioButton rbShred;
  TQRadioButton rbMkdir;
  TQRadioButton rbMimetype;

  // progress stuff
  TQButtonGroup progressButtons;

  TQRadioButton rbProgressNone;
  TQRadioButton rbProgressDefault;
  TQRadioButton rbProgressStatus;

  TQPushButton pbStart;
  TQPushButton pbStop;

  TQPushButton close;


private  Job job;
private  TQWidget main_widget;

private  StatusbarProgress statusProgress;

private  int selectedOperation;
private  int progressMode;
private  int putBuffer;
private  Slave slave;

 /*
  This file is or will be part of KDE desktop environment

  Copyright 1999 Matt Koss <koss@miesto.sk>

  It is licensed under GPL version 2.

  If it is part of KDE libraries than this file is licensed under
  LGPL version 2.
 */





KioslaveTest( String src, String dest, int op, int pr )
{
  super(null, "");
  job = null;

  main_widget = new TQWidget( this, "");
  TQBoxLayout topLayout = new TQVBoxLayout( main_widget, 10, 5 );

  TQGridLayout grid = new TQGridLayout( 2, 2, 10 );
  topLayout.addLayout( grid );

  grid.setRowStretch(0,1);
  grid.setRowStretch(1,1);

  grid.setColStretch(0,1);
  grid.setColStretch(1,100);

  lb_from = new TQLabel( "From :", main_widget );
  grid.addWidget( lb_from, 0, 0 );

  le_source = new TQLineEdit( main_widget );
  grid.addWidget( le_source, 0, 1 );
  le_source.setText( src );

  lb_to = new TQLabel( "To :", main_widget );
  grid.addWidget( lb_to, 1, 0 );

  le_dest = new TQLineEdit( main_widget );
  grid.addWidget( le_dest, 1, 1 );
  le_dest.setText( dest );

  // Operation groupbox & buttons
  opButtons = new TQButtonGroup( "Operation", main_widget );
  topLayout.addWidget( opButtons, 10 );
  connect( opButtons, SIGNAL("clicked(int)"), SLOT("changeOperation(int)") );

  TQBoxLayout hbLayout = new TQHBoxLayout( opButtons, 15 );

  rbList = new TQRadioButton( "List", opButtons );
  opButtons.insert( rbList, List );
  hbLayout.addWidget( rbList, 5 );

  rbListRecursive = new TQRadioButton( "ListRecursive", opButtons );
  opButtons.insert( rbListRecursive, ListRecursive );
  hbLayout.addWidget( rbListRecursive, 5 );

  rbStat = new TQRadioButton( "Stat", opButtons );
  opButtons.insert( rbStat, Stat );
  hbLayout.addWidget( rbStat, 5 );

  rbGet = new TQRadioButton( "Get", opButtons );
  opButtons.insert( rbGet, Get );
  hbLayout.addWidget( rbGet, 5 );

  rbPut = new TQRadioButton( "Put", opButtons );
  opButtons.insert( rbPut, Put );
  hbLayout.addWidget( rbPut, 5 );

  rbCopy = new TQRadioButton( "Copy", opButtons );
  opButtons.insert( rbCopy, Copy );
  hbLayout.addWidget( rbCopy, 5 );

  rbMove = new TQRadioButton( "Move", opButtons );
  opButtons.insert( rbMove, Move );
  hbLayout.addWidget( rbMove, 5 );

  rbDelete = new TQRadioButton( "Delete", opButtons );
  opButtons.insert( rbDelete, Delete );
  hbLayout.addWidget( rbDelete, 5 );

  rbShred = new TQRadioButton( "Shred", opButtons );
  opButtons.insert( rbShred, Shred );
  hbLayout.addWidget( rbShred, 5 );

  rbMkdir = new TQRadioButton( "Mkdir", opButtons );
  opButtons.insert( rbMkdir, Mkdir );
  hbLayout.addWidget( rbMkdir, 5 );

  rbMimetype = new TQRadioButton( "Mimetype", opButtons );
  opButtons.insert( rbMimetype, Mimetype );
  hbLayout.addWidget( rbMimetype, 5 );

  opButtons.setButton( op );
  changeOperation( op );

  // Progress groupbox & buttons
  progressButtons = new TQButtonGroup( "Progress dialog mode", main_widget );
  topLayout.addWidget( progressButtons, 10 );
  connect( progressButtons, SIGNAL("clicked(int)"), SLOT("changeProgressMode(int)") );

  hbLayout = new TQHBoxLayout( progressButtons, 15 );

  rbProgressNone = new TQRadioButton( "None", progressButtons );
  progressButtons.insert( rbProgressNone, ProgressNone );
  hbLayout.addWidget( rbProgressNone, 5 );

  rbProgressDefault = new TQRadioButton( "Default", progressButtons );
  progressButtons.insert( rbProgressDefault, ProgressDefault );
  hbLayout.addWidget( rbProgressDefault, 5 );

  rbProgressStatus = new TQRadioButton( "Status", progressButtons );
  progressButtons.insert( rbProgressStatus, ProgressStatus );
  hbLayout.addWidget( rbProgressStatus, 5 );

  progressButtons.setButton( pr );
  changeProgressMode( pr );

  // statusbar progress widget
  statusProgress = new StatusbarProgress( statusBar() );
  statusBar().addWidget( statusProgress, 0, true );

  // run & stop butons
  hbLayout = new TQHBoxLayout( topLayout, 15 );

  pbStart = new TQPushButton( "&Start", main_widget );
  pbStart.setFixedSize( pbStart.sizeHint() );
  connect( pbStart, SIGNAL("clicked()"), SLOT("startJob()") );
  hbLayout.addWidget( pbStart, 5 );

  pbStop = new TQPushButton( "Sto&p", main_widget );
  pbStop.setFixedSize( pbStop.sizeHint() );
  pbStop.setEnabled( false );
  connect( pbStop, SIGNAL("clicked()"), SLOT("stopJob()") );
  hbLayout.addWidget( pbStop, 5 );

  // close button
  close = new TQPushButton( "&Close", main_widget );
  close.setFixedSize( close.sizeHint() );
  connect(close, SIGNAL("clicked()"), this, SLOT("slotQuit()"));

  topLayout.addWidget( close, 5 );

  main_widget.setMinimumSize( main_widget.sizeHint() );
  setCentralWidget( main_widget );

  slave = null;
//  slave = Scheduler.getConnectedSlave(new KURL("ftp://ftp.kde.org"));
  Scheduler.connect(SIGNAL("slaveConnected(Slave)"),
	this, SLOT("slotSlaveConnected()"));
  Scheduler.connect(SIGNAL("slaveError(Slave,int,String)"),
	this, SLOT("slotSlaveError()"));
}


protected void closeEvent( TQCloseEvent e ){
  slotQuit();
}


void slotQuit(){
  if ( job != null ) {
    job.kill( true );  // kill the job quietly
  }
  if (slave != null )
    Scheduler.disconnectSlave(slave);
  TDEApplication.kApplication().quit();
}


void changeOperation( int id ) {
  // only two urls for copy and move
  boolean enab = rbCopy.isChecked() || rbMove.isChecked();

  le_dest.setEnabled( enab );

  selectedOperation = id;
}


void changeProgressMode( int id ) {
  progressMode = id;

  if ( progressMode == ProgressStatus ) {
    statusBar().show();
  } else {
    statusBar().hide();
  }
}


void startJob() {
 String sCurrent = TQDir.currentDirPath()+"/";
  KURL.encode_string(sCurrent);
  String sSrc = le_source.text();
  KURL src = new KURL( new KURL(sCurrent), sSrc );

  if ( !src.isValid() ) {
    TQMessageBox.critical(this, "Kioslave Error Message", "Source URL is malformed" );
    return;
  }

  String sDest = le_dest.text();
  KURL dest = new KURL( new KURL(sCurrent), sDest );

  if ( !dest.isValid() &&
       ( selectedOperation == Copy || selectedOperation == Move ) ) {
    TQMessageBox.critical(this, "Kioslave Error Message",
                       "Destination URL is malformed" );
    return;
  }

  pbStart.setEnabled( false );

  boolean observe = true;
  if (progressMode != ProgressDefault) {
    observe = false;
  }

  SimpleJob myJob = null;

  switch ( selectedOperation ) {
  case List:
    myJob = TDEIO.listDir( src );
//    connect(myJob, SIGNAL(" entries( Job, const TDEIO.UDSEntryList&)"),
//            SLOT(" slotEntries( TDEIO.Job, const TDEIO.UDSEntryList&)"));
    break;

  case ListRecursive:
    myJob = TDEIO.listRecursive( src );
//    connect(myJob, SIGNAL(" entries( TDEIO.Job, const TDEIO.UDSEntryList&)"),
 //           SLOT(" slotEntries( TDEIO.Job, const TDEIO.UDSEntryList&)"));
    break;

  case Stat:
    myJob = TDEIO.stat( src );
    break;

  case Get:
    myJob = TDEIO.get( src, true );
     connect(myJob, SIGNAL("data( Job, byte[])"),
            SLOT("slotData( Job, byte[])"));
   break;

  case Put:
    putBuffer = 0;
    myJob = TDEIO.put( src, -1, true, false);
    connect(myJob, SIGNAL("dataReq( Job, ByteArrayOutputStream)"),
            SLOT("slotDataReq( Job, ByteArrayOutputStream)"));
    break;

  case Copy:
    job = TDEIO.copy( src, dest, observe );
    break;

  case Move:
    job = TDEIO.move( src, dest, observe );
    break;

  case Delete:
    job = TDEIO.del( src, false, observe );
    break;

  case Shred:
    job = TDEIO.del(src, true, observe);
    break;

  case Mkdir:
    myJob = TDEIO.mkdir( src );
    break;

  case Mimetype:
    myJob = TDEIO.mimetype( src );
    break;
  }
  if (myJob != null)
  {
    if (slave != null)
      Scheduler.assignJobToSlave(slave, myJob);
    job = myJob;
  }

  connect( job, SIGNAL(" result( Job  )"),
           SLOT(" slotResult( Job  )") );

  connect( job, SIGNAL(" canceled( Job  )"),
           SLOT(" slotResult( Job  )") );

  if (progressMode == ProgressStatus) {
    statusProgress.setJob( job );
  }

  pbStop.setEnabled( true );
}


void slotResult(Job  _job )
{
  if ( _job.error() != 0 )
  {
    _job.showErrorDialog();
  }
  else if ( selectedOperation == Stat )
  {
//      UDSEntry entry = ((TDEIO.StatJob)_job).statResult();
//      printUDSEntry( entry );
  }
  else if ( selectedOperation == Mimetype )
  {
      System.out.println("mimetype is " + ((MimetypeJob)_job).mimetype());
  }

  if (job == _job)
     job = null;
  pbStart.setEnabled( true );
  pbStop.setEnabled( false );
}

void slotSlaveConnected()
{
     System.out.println("Slave connected.");
}

void slotSlaveError()
{
     System.out.println("Error connected.");
   slave = null;
}

/*
void UDSEntry & entry )
{
    TDEIO.UDSEntry.ConstIterator it = entry.begin();
    for( ; it != entry.end(); it++ ) {
        switch ((it).m_uds) {
            case TDEIO.UDS_FILE_TYPE:
                kdDebug() << "File Type : " << (mode_t)((it).m_long) << endl;
                if ( S_ISDIR( (mode_t)((it).m_long) ) )
                {
                    kdDebug() << "is a dir" << endl;
                }
                break;
            case TDEIO.UDS_ACCESS:
                kdDebug() << "Access permissions : " << (mode_t)((it).m_long) << endl;
                break;
            case TDEIO.UDS_USER:
                kdDebug() << "User : " << ((it).m_str.ascii() ) << endl;
                break;
            case TDEIO.UDS_GROUP:
                kdDebug() << "Group : " << ((it).m_str.ascii() ) << endl;
                break;
            case TDEIO.UDS_NAME:
                kdDebug() << "Name : " << ((it).m_str.ascii() ) << endl;
                //m_strText = decodeFileName( (it).m_str );
                break;
            case TDEIO.UDS_URL:
                kdDebug() << "URL : " << ((it).m_str.ascii() ) << endl;
                break;
            case TDEIO.UDS_MIME_TYPE:
                kdDebug() << "MimeType : " << ((it).m_str.ascii() ) << endl;
                break;
            case TDEIO.UDS_LINK_DEST:
                kdDebug() << "LinkDest : " << ((it).m_str.ascii() ) << endl;
                break;
        }
    }
}

void UDSEntryList& list) {

    UDSEntryListConstIterator it=list.begin();
    for (; it != list.end(); ++it) {
        UDSEntry.ConstIterator it2 = (it).begin();
        for( ; it2 != (it).end(); it2++ ) {
            if ((it2).m_uds == UDS_NAME)
                kdDebug() << "" << ( it2 ).m_str << endl;
        }
    }
}
*/

void slotData(Job job, byte[] data)
{
    if (data.length == 0)
    {
       System.out.println("Data: <End>");
    }
    else
    {
       String myString = new String(data);
       System.out.println("Data: \"" + myString + "\"");
    }
}

void slotDataReq(Job job, ByteArrayOutputStream data)
{
    String[] fileDataArray =
       {
         "Hello world\n",
         "This is a test file\n",
         "You can safely delete it.\n",
		 null
       };
    String fileData = fileDataArray[putBuffer++];

    if (fileData == null)
    {
       System.out.println("DataReq: <End>");
       return;
    }

	try {
		data.write(fileData.getBytes());
	} catch (java.io.IOException e) {
		;
	}

	System.out.println("DataReq: \"" + fileData + "\"");
}

void stopJob() {
  System.out.println("KioslaveTest.stopJob()");
  job.kill();
  job = null;

  pbStop.setEnabled( false );
  pbStart.setEnabled( true );
}

static String version = "v0.0.0 0000";   // :-)
static String description = "Test for tdeioslaves";
static String[][] options =
{
 { "s", null, null },
 { "src <src>", "Source URL", "" },
 { "d", null, null },
 { "dest <dest>", "Destination URL", "" },
 { "o", null, null },
 { "operation <operation>", "Operation (list,listrecursive,stat,get,copy,move,del,shred,mkdir)", "copy" },
 { "p", null, null },
 { "progress <progress>", "Progress Type (none,default,status)", "default" }
};

public static void main(String[] argv) {
  TDECmdLineArgs.init( argv, "tdeioslavetest", "KIOSlaveTest", description, version );
  TDECmdLineArgs.addCmdLineOptions( options );
  TDEApplication app = new TDEApplication();

  TDECmdLineArgs args = TDECmdLineArgs.parsedArgs();

  String src = args.getOption("src");
  String dest = args.getOption("dest");

  int op = 0;
  int pr = 0;

  String tmps;

  tmps = args.getOption("operation");
  if ( tmps.equals("list")) {
    op = KioslaveTest.List;
  } else if ( tmps.equals("listrecursive")) {
    op = KioslaveTest.ListRecursive;
  } else if ( tmps.equals("stat")) {
    op = KioslaveTest.Stat;
  } else if ( tmps.equals("get")) {
    op = KioslaveTest.Get;
  } else if ( tmps.equals("copy")) {
    op = KioslaveTest.Copy;
  } else if ( tmps.equals("move")) {
    op = KioslaveTest.Move;
  } else if ( tmps.equals("del")) {
    op = KioslaveTest.Delete;
  } else if ( tmps.equals("shred")) {
    op = KioslaveTest.Shred;
  } else if ( tmps.equals("mkdir")) {
    op = KioslaveTest.Mkdir;
  } else TDECmdLineArgs.usage("unknown operation");

  tmps = args.getOption("progress");
  if ( tmps.equals("none")) {
    pr = KioslaveTest.ProgressNone;
  } else if ( tmps.equals("default")) {
    pr = KioslaveTest.ProgressDefault;
  } else if ( tmps.equals("status")) {
    pr = KioslaveTest.ProgressStatus;
  } else TDECmdLineArgs.usage("unknown progress mode");

  args.clear(); // Free up memory

  KioslaveTest test = new KioslaveTest( src, dest, op, pr );
  test.show();
  // Bug in KTMW / Qt / layouts ?
  test.resize( test.sizeHint() );

  app.setMainWidget(test);
  app.exec();
  return;
}

	static {
		qtjava.initialize();
		tdejava.initialize();
	}
}


