#! /usr/bin/python

import socket
import sys
import os
import os.path
import json
import traceback
import shlex
from args import *
from job import *
from driver import *
      
def usage():
  print "usage 1: ./exporter.py [--port/-p wrapper_communication_port] [--base/-b base_dir] [--out/-o out_dir] input_file1.src,input_file2.src,..."
  print "  Exports the assets specified in the given source file(s)"
  print
  print "usage 2: ./exporter.py [--port/-p wrapper_communication_port] [--base/-b base_dir] [--out/-o out_dir] -"
  print "  Reads full command lines (everything except --port) as lines from stdin"
  print
  print "usage 3: ./export.py  --help|-h"
  print "  Shows this help message"

if "-h" in sys.argv or "--help" in sys.argv:
  usage()
  sys.exit(0)

(err, args) = ArgParser().parse_args(sys.argv[1:])
if err is not None:
  print err
  usage()
  sys.exit(2)

from_stdin = False
if "-" in args["input"]:
  from_stdin = True
  if len(args["input"]) > 1:
    print "If reading from stdin ('-') is specified, no other input may be given"
    usage()
    sys.exit(2)

if not len(args["input"]):
  usage()
  sys.exit(0)

port = args["port"] if "port" in args else 7890

jobs = {}
sent_all_jobs = False
driver = Driver(port, from_stdin)

def send_cmd(cmd, **kwargs):
  global driver
  kwargs["command"] = cmd
  driver.send_json(kwargs)

def send_job(job):
  send_cmd("job", **job.get_cmd())

def check_jobs_done():
  global sent_all_, jobs
  return sent_all_jobs and not len(jobs)

if not from_stdin:
  base_args = make_base_job_args(args)
  for i in args["input"]:
    try:
      job = Job(input = i, **base_args)
      jobs[job.id] = job
    except Exception, e:
      print e
  sent_all_jobs = True
  if check_jobs_done():
    sys.exit(0)

driver_started = driver.start()

if driver_started:
  if not from_stdin:
    for id in jobs:
      send_job(jobs[id])

def handle_stdin(line):
  global sent_all_jobs, jobs
  if line is None:
    sent_all_jobs = True
    if check_jobs_done():
      return False
    return True
  parts = shlex.split(line)
  (err, line_args) = ArgParser.parse_args(parts)
  if err is not None:
    print err
  else:
    base_args = make_base_job_args(dict(args.items() + line_args.items()))
    for i in line_args["input"]:
      try:
        job = Job(input = i, **base_args)
        jobs[job.id] = job
      except Exception, e:
        print e
      send_job(job)
  return True

def handle_command(msg_str):
  # return False to quit the driver loop
  msg = json.loads(msg_str)
  if "command" in msg:
    cmd = msg["command"]
    if cmd == "exit":
      return False
    if cmd == "print" and "string" in msg:
      sys.stdout.write(msg["string"])
      sys.stdout.flush()
    if cmd == "done" and "id" in msg:
      id = int(msg["id"])
      if id in jobs:
        jobs.pop(id)
        if check_jobs_done():
          return False
  return True

# still have to loop() even if we didn't start succesfully,
# as we may be waiting for the exporter process to close
driver.loop(handle_command, handle_stdin)
