#! /usr/bin/env python3
"""
"""

from __future__ import print_function
from __future__ import unicode_literals
import subprocess
import os, sys, inspect, logging, shutil, re, json, hashlib, tempfile, stat, io
from argparse import ArgumentParser
import pyparsing as pp
from datetime import datetime

def cmd_time(arguments):
  parser = ArgumentParser(description="Extract timing information from log files.")

  parser.add_argument("file",
                      action="store",
                      nargs="*",
                      help="Files to report time information on." )

  args = parser.parse_args(arguments)

  class parser:
    begin = pp.Literal("BEGIN:")+pp.Word(pp.nums)('date')+pp.Word(pp.nums+':')('time')
    end   = pp.Literal("END:")  +pp.Word(pp.nums)('date')+pp.Word(pp.nums+':')('time')
    cmd   = pp.Literal("CMD:")  +pp.Word(pp.printables)('command')
    args  = pp.Literal("ARGS:") +pp.Word(pp.printables)('arguments')

  for file in args.file:
    print("file:",file)
    with open(file,'r') as f:
      text = f.read()

    begin = parser.begin.searchString(text)
    end   = parser.end.searchString(text)
    cmd   = parser.cmd.searchString(text)
    args  = parser.args.searchString(text)

    for i in range(len(cmd)):
      print("\tcmd:",cmd[i]["command"])
      print("\targ:"," ".join([ args[i]["arguments"] for i in range(len(args)) ]))
      if(len(begin) < 1):
        print("\tHas not started yet")
      else:
        begin_datetime = datetime.strptime('{} {}'.format(begin[i]["date"],begin[i]["time"]), '%Y%m%d %H:%M:%S')
        if(len(end) < 1):
          print("\tHas not finished yet")
        else:
          end_datetime = datetime.strptime('{} {}'.format(end[i]["date"],end[i]["time"]), '%Y%m%d %H:%M:%S')
          duration = end_datetime-begin_datetime
          print("\tduration:",duration)





#  __  __       _       
# |  \/  | __ _(_)_ __  
# | |\/| |/ _` | | '_ \ 
# | |  | | (_| | | | | |
# |_|  |_|\__,_|_|_| |_|
                      


funcmembers = [ func for func in inspect.getmembers(sys.modules[__name__], inspect.isfunction) if func[0].lower().startswith("cmd_") ]
commands = { k.lower().replace("cmd_",""):v for (k,v) in funcmembers}

def main():
  parser = ArgumentParser(description="A tool to perform various tasks related to running jobs.")

  parser.add_argument("command",
                      action="store",
                      help="sub-command." )

  parser.add_argument("command_args",
                      action="store",
                      nargs="*",
                      help="sub-command arguments/options." )

  parser.add_argument("-m", "--manual",
                      action="store_true",
                      help="Print manual and exit." )

  parser.add_argument("-l","--list-commands",
                      action="store_true",
                      default=False,
                      help="List supported handlers and exit." )

  parser.add_argument("--debug",
                      action="store_true",
                      default=False,
                      help="Turn on debugging output." )


  command_index = None
  try: command_index = sys.argv.index( next( x for x in sys.argv[1:] if not x.startswith('-') ) )
  except: pass
  main_args = sys.argv[:command_index]
  cmd_args = sys.argv[command_index:]
  args = parser.parse_args(main_args)

  if args.manual:
    print(__doc__)
    sys.exit()

  if args.list_commands:
    print("Commands:")
    for c in commands:
      print("  ",c)
    sys.exit()

  if args.debug:
    logging.basicConfig(level=logging.DEBUG)

  if not cmd_args[0] in commands:
    raise RuntimeError("Unknown command '{cmd}'. Use the '-l' option to see a list of supported commands.".format(cmd=cmd_args[0]))

  commands[cmd_args[0]]( cmd_args[1:] )

if __name__ == "__main__":
  main()
