/* Software- und Organisations-Service GmbH, 2005, www.sos-berlin.com
   Andreas Püschel, 2005-05-30, andreas.pueschel@sos-berlin.com

   This script simply moves files from an input directory to an output directory
   and demonstrates the usage of the Job Scheduler API methods for logging and error handling:
*/


  try {
    var directories = spooler_task.changed_directories();
    var directoryPaths = directories.split(";");

    for(var i=0; i<directoryPaths.length; i++) {
      if (directoryPaths[i].length == 0) continue;

      var directory     = new java.io.File(directoryPaths[i]);
      // fetch a list of files in the given directory that match the regular expression
      var files         = new sos.util.SOSFile.getFilelist(directory.getCanonicalPath(), ".*", 0);

      var filesIterator = files.iterator();
      while (filesIterator.hasNext()) {
        var inputFile = filesIterator.next();
        var outputFile = new java.io.File(spooler_task.params.value("output_directory") + "/" + String(inputFile.getName()));
        if (outputFile.exists()) {
         if (!sos.util.SOSFile.deleteFile(outputFile)) {
             spooler_log.warn("working file probably in use, trying later: " + String(outputFile.getCanonicalPath()));
             continue;
          }
        }
        if (!inputFile.renameTo(outputFile)) {
          spooler_log.warn("could not rename input file [" + String(inputFile.getCanonicalPath()) + "] " +
                           "to output file [" + String(outputFile.getCanonicalPath()) + "]");
        } else {
          spooler_log.info("input file [" + String(inputFile.getCanonicalPath()) + "] " +
                           "successfully moved to output file [" + String(outputFile.getCanonicalPath()) + "]");
        }
      }
    }
  } catch (e) {
    spooler_log.warn("error occurred triggering input files: " + String(e));
 }