#!/usr/bin/env python
# jet.py

"""
Author : peters 

Revision History:
File created on 06 Sep 2010.

"""

import sys
import os
import logging
import subprocess

from da.baseclasses.platform import PlatForm

std_joboptions={'jobname':'test','jobaccount':'co2','jobnodes':'2','jobshell':'/bin/sh','depends':'','jobtime':'00:30:00','joblog':os.getcwd()}

class ZeusPlatForm(PlatForm):
    def __init__(self):
        self.Identifier     = 'NOAA zeus'    # the identifier gives the platform name
        self.Version        = '1.0'     # the platform version used

        msg1  = '%s platform object initialized'%self.Identifier ; logging.debug(msg1)
        msg2  = '%s version: %s'%(self.Identifier,self.Version) ; logging.debug(msg2)

    def ReturnBlockingFlag(self):

        return ""

    def ReturnQueueType(self):

        return "foreground"


    def get_job_template(self,joboptions={},block=False):
        """ Return the job template for a given computing system, and fill it with options from the dictionary provided as argument"""

        template = """#!/bin/sh \n"""+ \
                   """#PBS -N jobname \n"""+ \
                   """#PBS -A jobaccount \n"""+ \
                   """#PBS -l procs=jobnodes \n"""+ \
                   """#PBS -l walltime=jobtime \n"""+ \
                   """source /usr/share/Modules/init/sh\n"""+ \
                   """module load intel\n"""+ \
                   """module load mpt\n"""+ \
                   """module load numpy/1.6.1\n"""+ \
                   """module load netcdf4-python/0.9.7\n"""
        if 'depends' in joboptions:
            template += """#$ -hold_jid depends \n"""

       # if block:
       #     template += """#$ -sync y\n"""

        # First replace from passed dictionary
        for k,v in joboptions.iteritems():
            while k in template:
                template = template.replace(k,v)

        # Fill remaining values with std_options
        for k,v in std_joboptions.iteritems():
            while k in template:
                template = template.replace(k,v)

        return template

    def get_my_id(self):
        try:
            return os.environ['JOB_ID']
        except:
            return os.getpid()

    def submit_job(self,jobfile,joblog=None,block=False): 
        """ This method submits a jobfile to the queue, and returns the queue ID """

        if block:
            cmd     = ["qsub","-X","-W block=T",jobfile]
            msg = "A new task will be started (%s)"%cmd  ; logging.info(msg)
            output  = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]  ; logging.info(output)
            print 'block','true'
            jobid   = output.split('.bqs1.zeus')[0]
            print 'jobid',jobid
        else:
            cmd     = ["qsub",jobfile]
            msg = "A new task will be started (%s)"%cmd  ; logging.info(msg)
            output  = subprocess.Popen(cmd, stdout=subprocess.PIPE).communicate()[0]  ; logging.info(output)
            print 'block','false'
            jobid   = output.split('.bqs1.zeus')[0]
            print 'jobid',jobid

        return jobid



    def kill_job(self,jobid):                   
        """ This method kills a running job """
        
        output = subprocess.Popen(['qdel',jobid], stdout=subprocess.PIPE).communicate()[0]  ; logging.info(output)

        return output

    def job_stat(self,jobid):                   
        """ This method gets the status of a running job """
        import subprocess
        
        #output = subprocess.Popen(['sgestat'], stdout=subprocess.PIPE).communicate()[0]  ; logging.info(output)

        return ''

if __name__ == "__main__":
    pass
