#include <iostream>
#include <string>

#include "glite/lb/JobStatus.h"
#include "glite/wmsutils/exception/Exception.h"
#include "glite/wms/jdl/JobAd.h"
#include "glite/wmsui/api/Job.h"


using namespace std ;
using namespace glite::wms::common::utilities;
using namespace glite::wmsutils::jobid;
using namespace glite::wms::jdl;
using namespace glite::wmsui::api;
using namespace glite::lb;


int main (int argc,char *argv[])
{

  cout << "Workload Management API Example " << endl;
  
  try{
    if (argc < 6 ||  strcmp(argv[1],"--help") == 0)  {
      cout << "Usage : " << argv[0] 
	   << "  <JDL file>  <ns host> <ns port> <lbHost> <lbPort> [<ce_id>]" 
	   << endl;
      return -1;
    }

    JobAd jab;
    
    jab.fromFile ( argv[1] ) ;
    
    jab.setDefaultReq ("other.GlueCEStateStatus == \"Production\"") ;
    jab.setDefaultRank ("-other.GlueCEStateEstimatedResponseTime");
  
    glite::wmsui::api::Job   job(jab);
    job.setLoggerLevel (6) ;
    
    cout << "Submit job to " << argv[2] << ":" <<  argv[3]  << endl;
    cout << "LB address: "<< argv[4] << ":" <<  argv[5]  << endl;
    cout << "Please wait..." << endl;

    // We now submit the job. If a CE is given (argv[6]), we send it directly 
    // to the specified CE
    //
    if (argc ==6)
      job.submit (argv[2], atoi(argv[3]), argv[4], atoi(argv[5]),  "") ;
    else
      job.submit (argv[2], atoi(argv[3]), argv[4], atoi(argv[5]), argv[6] ) ;

    glite::wmsutils::jobid::JobId jid(job.getJobId()->toString());

    cout << "Job Submission OK; JobID= "  
	 <<  job.getJobId()->toString() << endl << flush ;
     
    // Now that the job has successfully finished, we retrieve the output
    //
    
    return 0;
    
  } catch (std::exception &exc){
    cerr << "\nWMS Error\n";
    cerr <<  exc.what();
  }    
  return -1;
}
