#!/usr/bin/python3
import sys, getopt, os
import time, json
import pprint
from ol_constants import *
from datetime import datetime
from ol_event import arrayindicies, eshostname
from ol_query import query_add, timeformat
from elasticsearch import Elasticsearch
from ol_displayjobs import print_long_format, print_custom_format, print_json_format
import subprocess

noheader  = False
fintimeformat = 0
alljobs = 0

es = Elasticsearch(eshostname())
indexname = 'jobs'

mycommand = sys.argv[0]
cmdlen=len(sys.argv[0])

def usage():
    print('Usage: ' + mycommand + ' [-h] [-V] [-w |-l |-j] [-W] [-a] [-d] [-p] [-s] [-r] [-g job_group]')
    print(' '*(8+cmdlen) + '[-A] [-m host_name] [-q queue_name] [-u user_name | -u all]')
    print(' '*(8+cmdlen) + '[-P project_name] [-J name_spec] [-UF] [-WL|-WP|-WF] [-noheader]')
    print(' '*(8+cmdlen) + '[-o "field_name ... [delimiter=\'character\']]"')
    print(' '*(8+cmdlen) + '[jobId | "jobId[idxList]" ...')
    sys.exit(-1)

try:
    opts, args = getopt.getopt(sys.argv[1:], "VljadpsrwW:RAhJ:q:u:m:n:o:P:SU:g:")
except getopt.GetoptError:
    print ('Invalid option')
    usage()

jobstatus = set([])
user = os.getenv("USER")
queue = ''
host = ''
jobName = []
format = 0
option = 0
job_group = ''
projectName = ''

for opt, arg in opts:
    if opt == '-h':
        usage()
    elif opt == '-V':
        print('SkyForm AI cjobs, v1.0')
        sys.exit(0)
    elif opt == '-w':
        if (format == LONG_FORMAT) or (format == UF_FORMAT) or \
           (format == CUSTOM_FORMAT) or (fintimeformat > 0):
            usage()
        format = WIDE_FORMAT
    elif opt == '-l':
        if (format == WIDE_FORMAT) or (format == CUSTOM_FORMAT) or \
           (fintimeformat > 0):
            usage()
        if format != UF_FORMAT:
            format = LONG_FORMAT
    elif opt == '-j':
        format = JSON_FORMAT
    elif opt == '-a':
        alljobs = 1
    elif opt == '-d':
        jobstatus.add('DONE')
        jobstatus.add('EXIT')
    elif opt == '-p':
        jobstatus.add('PEND')
        jobstatus.add('PSUSP')
        alljobs = 2 
    elif opt == '-s':
        jobstatus.add('SSUSP')
        jobstatus.add('USUSP')
        jobstatus.add('PSUSP')
    elif opt == '-r':
        jobstatus.add('RUN') 
    elif opt == '-A':
        option = JGRP_ARRAY
    elif opt == '-J':
        jobName = [arg, arg+"[*"]
    elif opt == '-q':
        queue = arg
    elif opt == '-u':
        if arg.lower() == 'all':
            user = 'all'
        else:
            user = arg
    elif opt == '-m':
        host = "*"+arg
    elif opt == '-o':
        if (format == LONG_FORMAT) or (format == UF_FORMAT) or \
           (format == WIDE_FORMAT) or (fintimeformat != 0):
            usage()
        format = CUSTOM_FORMAT
        cusFormat = arg
    elif opt == '-P':
        projectName = arg
    elif opt == '-W':
        if format == CUSTOM_FORMAT:
            usage()
        if arg == '':
            format = WWIDE_FORMAT
        else:
            if arg == 'L':
                fintimeformat = FORMAT_WL
            elif arg == 'P':
                fintimeformat = FORMAT_WP
            elif arg == 'F':
                fintimeformat = FORMAT_WF
            else:
                print('Invalid option')
                usage()
    elif (opt == '-U') and (arg == 'F'):
        format = UF_FORMAT
    elif (opt == '-n' ):
        if(arg == 'oheader'):
            if (format == 0) or (format == WIDE_FORMAT) or (format == CUSTOM_FORMAT):
                noheader = True
    elif opt == '-g':
        job_group = arg
    else:
        print('Invalid option')
        usage()

if len(jobstatus) == 0:
    jobstatus=set(['RUN','PEND','USUSP','PSUSP','SSUSP', 'UNKWN'])

if alljobs == 1:
    jobstatus=set([])

jobs = []
if len(args) > 0:
    for job in args:
        idxlist = arrayindicies(job)
        if idxlist == [0]:
            if not job.isdigit():
                 usage()
            jobs.append([int(job),0])
        else:
            job = job[0:job.find('[')]
            for idx in idxlist:
                if not job.isdigit():
                     usage()
                jobs.append([int(job),idx])
    user = 'all'
    jobstatus = []
else:
    jobs = []

query = {"query":{"bool":{"must":[]}}}
if len(jobstatus) > 0:
    query = query_add(query, "status", jobstatus, 1)
if user != 'all':
    query = query_add(query, "userName", user, 0)
if job_group != '':
    query = query_add(query, "jobGroup", job_group, 0)
if host != '':
    query = query_add(query, "execHosts", host, 3)
if queue != '':
    query = query_add(query, "queue", queue, 0)
if projectName != '':
    query = query_add(query, "projectName", projectName, 0)
if len(jobName) > 0:
    query = query_add(query, "jobName", jobName, 1)
if jobs != []:
    query = query_add(query, "jobId", jobs, 2)

cluster = subprocess.check_output(["ccluster"]).split()
type = cluster[6].decode('UTF-8')
# querystr = str(query).replace("'",'"')
# pprint.pprint (query)
result = es.search(index=indexname, body=query, size=MAX_QUERY)
result['hits']['hits'].sort(key=lambda x: (int(x['_source']['jobId']), int(x['_source']['idx'])))
jobs = result['hits']['hits']
if len(jobs) == 0:
    if (len(jobstatus) > 0) and ('DONE' not in jobstatus):
        print('No unfinished job found')
    else:
        print('No job found')
    sys.exit(-1)

if (noheader == False) and (format != UF_FORMAT) and (format != LONG_FORMAT) and (format != CUSTOM_FORMAT) and (format != JSON_FORMAT):
    print('JOBID   USER    STAT  QUEUE      FROM_HOST   EXEC_HOST   JOB_NAME   SUBMIT_TIME   ', end='')
    if fintimeformat == FORMAT_WL:
        print('TIME_LEFT')
    elif fintimeformat == FORMAT_WP:
        print('%COMPLETE')
    elif fintimeformat == FORMAT_WF:
        print('FINISH_TIME')
    else:
        print()

first = True
jsonjobs = []
for jobdata in jobs:
    job = jobdata['_source']

    if (format == UF_FORMAT) or (format == LONG_FORMAT):
        print_long_format(format, job)
        if jobdata == jobs[-1]:
            print()
        else:
            print('-'*79)
        continue
    elif format == CUSTOM_FORMAT:
        print_custom_format(noheader, cusFormat, job, first)
        first = False
        continue
    elif format == JSON_FORMAT:
        jsonjobs.append(print_json_format(job))
        continue

    if (format != WIDE_FORMAT) and (format != WWIDE_FORMAT):
        l = len(job['jobName'])
        if l > 10:
            job['jobName'] = '*' + job['jobName'][l-9:]
    if format == WIDE_FORMAT:
        print('{:<7} {:<7} {:<5} {:<10} {:<11} {:<11} {:<10}'.format(job['jobId'], \
          job['userName'], job['status'], job['queue'], job['fromHost'], \
          " ".join(job['execHosts']), \
          job['jobName']), timeformat(job['submitTime'],"%b %d %H:%M"+'  '),end='')
    else:
        if job['numExHosts'] == 0:
            eh = ''
        else:
            eh = job['execHosts'][0][:11]
        print('{:<7} {:<7} {:<5} {:<10} {:<11} {:<11} {:<10}'.format(job['jobId'], \
          job['userName'][:7], job['status'], job['queue'][:10], job['fromHost'][:11], \
          eh, \
          job['jobName']), timeformat(job['submitTime'],"%b %d %H:%M"+'  '),end='')
    runlimit = int(job['rLimits'][RLIMIT_RUN])/int(float(job['hostFactor']))
    if fintimeformat == FORMAT_WL:
        if (runlimit >= 0) and (job['startTime']!='') and (job['endTime'] ==''):
            now = time.time()
            remain = int((time.mktime(datetime.strptime(job['startTime'], "%Y-%m-%d %H:%M:%S").timetuple()) + \
                     runlimit - now)/60)
            print (str(int(remain/60))+':'+str(int(remain%60))+' L')
        else:
            print ('   -')
    elif fintimeformat == FORMAT_WP:
        if (runlimit >= 0) and (job['startTime']!='') and (job['endTime'] ==''):
            now = time.time()
            completed = float(now - time.mktime(datetime.strptime(job['startTime'], "%Y-%m-%d %H:%M:%S").timetuple()))/float(runlimit)*100.0
            print('%.2f%%'%completed,'L')
        else:
            print ('   -')
    elif fintimeformat == FORMAT_WF:
        if job['endTime'] != '':
            print(timeformat(job['submitTime'],"%b %d %H:%M"))
        else:
            if (runlimit >= 0) and (job['startTime']!=''):
                esendtime = time.mktime(datetime.strptime(job['startTime'], "%Y-%m-%d %H:%M:%S").timetuple()) + runlimit
                print(datetime.fromtimestamp(esendtime).strftime('%b %d %H:%M'))
            else:
                print('   -') 
    else:
        print()
    if (len(job['execHosts']) > 1) and (format != WIDE_FORMAT):
        for eh in job['execHosts'][1:]:
            print(' '*44,'{:<11}'.format(eh))
    if alljobs == 2:
        print(job['pendReasons'].replace('\n',''))
if format == JSON_FORMAT:
    print(json.dumps(jsonjobs, indent=2))
