#!/usr/bin/env python

"""xbundle_convert

Description:
    Convert between OLX and xbundle XML formats.
    If the input format in an XML file, the output will be OLX.
    If the input format is a directory, the output will be xbundle.

Usage:
    xbundle_convert convert [--force-studio] <input> <output>
    xbundle_convert test
    xbundle_convert --help | -h
    xbundle_convert --version

Options:
    --force-studio  forces <sequential> to be followed by <vertical> in export
    -h --help       show this screen
"""

# stdlib
import sys
from pkg_resources import get_distribution

# PyPi
from docopt import docopt

# local
from xbundle import XBundle, run_tests

# pylint: disable=star-args


def main():
    """
    Convert between OLX and xbundle XML formats.
    """
    # This parses the docstring above and derives all arguments.
    # If the required arguments are missing, it prints basic usage
    # and exits automatically.
    # If required arguments are satisfied, it returns a dict.
    args = docopt(__doc__, version=get_distribution("xbundle").version)

    options = dict(keep_urls=True)
    if args['--force-studio']:
        options['force_studio_format'] = True

    if args['test']:
        run_tests()
        return

    bundle = XBundle(**options)
    input_path = args['<input>']
    output_path = args['<output>']
    if input_path.endswith('.xml'):
        print("Converting xbundle '{0}' to edX directory '{1}'".format(
            input_path, output_path)
        )
        bundle.load(input_path)
        bundle.export_to_directory(output_path)
        print("done")
    elif output_path.endswith('.xml'):
        print("Converting edX directory '{0}' to xbundle '{1}'".format(
            input_path, output_path)
        )
        bundle.import_from_directory(input_path)
        bundle.save(output_path)
        print("done")
    else:
        print("Invalid input; run with --help for more info.")
        sys.exit(1)

if __name__ == '__main__':
    main()
