#! /usr/bin/env python

import os,sys,stat
import json,random
import re
from argparse import ArgumentParser
parser = ArgumentParser(description="Generate quiz files from a markdown quiz input file.")

parser.add_argument("-p", "--pythonpath",
                    action="store",
                    nargs='*',
                    default=['.'],
                    help="Additional paths to add to python module search path.")

parser.add_argument("-f", "--from",
                    action="store",
                    dest="_from",
                    default="markdown",
                    help="Input format")

parser.add_argument("-t", "--to",
                    action="store",
                    default="latex",
                    help="Output format")

parser.add_argument("-o", "--output",
                    action="store",
                    default="/dev/stdout",
                    help="Output file")

parser.add_argument("-x", "--overwrite",
                    action="store_true",
                    default=False,
                    help="Overwrite output file if it exists")

parser.add_argument("-s", "--skeleton",
                    action="store_true",
                    help="Write a skeleton file.")

parser.add_argument("input",
                    action="store",
                    nargs='?',
                    help="Input file containing quiz.")

parser.add_argument("--config",
                    action="store",
                    default=[],
                    nargs='*',
                    help="Configuration options that will be passed to the assignment class. These options will override any options in the quiz file.")

args = parser.parse_args()

sys.path += args.pythonpath
import pyAssignment.Readers as Readers
import pyAssignment.Writers as Writers
from pyAssignment.Utils import ColorCodes


if args.output != "/dev/stdout" and os.path.exists(args.output) and not args.overwrite:
  print("Output file (%s) exists. Use -x option if you want to overwrite."%args.output)
  sys.exit(1)



if args.skeleton:
  with open(args.output,'w') as f:
    f.write('''---
title: TITLE
---

# Questions

1. Question 1
    1. Answer 1
    1. Answer 2
''')
  sys.exit(0)

if args.input is None:
  parser.print_usage()
  sys.exit(1)

reader = None
writer = None

if args._from.lower() == 'markdown':
  reader = Readers.Markdown()
else:
  print("ERROR: unrecognized input format '{}'".format(args._from))
  sys.exit()


if args.to.lower() == 'latex':
  writer = Writers.Latex()
elif args.to.lower() == 'simple':
  writer = Writers.Simple()
elif args.to.lower() == 'blackboard':
  writer = Writers.BlackboardQuiz()
else:
  print("ERROR: unrecognized output format '{}'".format(args.to))
  sys.exit()

with open(args.input,'r') as f:
  ass = reader.load(f)

config_json = "{"+','.join(args.config)+"}"
try:
  config = json.loads( config_json )
  ass.meta.__dict__.update(config)
except:
  print("ERROR: could not parse configuration passed at command line")
  print("Note: this should be valid JSON")
  print( config_json )
  sys.exit(1)

if ass.meta.has('randomize_questions') and ass.meta.randomize_questions:
  random.shuffle(ass._questions)
if ass.meta.has('randomize_answers') and ass.meta.randomize_answers:
  for q in ass._questions:
    if hasattr(q._answer,'shuffle'):
      q._answer.shuffle()



with open(args.output,'w') as f:
  writer.dump(ass,f)

if args.to.lower() == 'blackboard':
  with open(args.output,'r') as f:
    text = f.read()
    ms = re.findall('\\\[a-zA-Z]+{',text)
    if len(ms) > 0:
      print(ColorCodes.WARNING, file=sys.stderr)
      print("WARNING: it appears that the quiz text ({}) contains one ore more LaTeX macros.".format(args.output), file=sys.stderr)
      print("         This is almost certainly *NOT* what you want.", file=sys.stderr)
      print("Possible Macros:", file=sys.stderr)
      i = 0
      for m in ms:
        print(i,m, file=sys.stderr)
        i += 1
      print(ColorCodes.ENDC, file=sys.stderr)





