import argparse
import os
import subprocess
import sys

import cascajal.profile


def _get_arg_parser():
    """Create the CLI arg parser for Cascajal."""

    parser = argparse.ArgumentParser(
        description='Generate PDF output for Hieroglyph presentations.',
    )
    parser.add_argument('--firefox',
                        dest='firefox',
                        action='store',
                        help='Location of firefox executable (default: guess)',
    )
    parser.add_argument('-o', '--output',
                        dest='output_filename',
                        action='store',
                        default='slides.pdf',
                        type=lambda s:os.path.abspath(os.path.expanduser(s)),
                        help='Output filename to write (default: slides.pdf)',
    )

    parser.add_argument('input_file',
                        metavar='presentation.html',
                        type=lambda s:os.path.abspath(os.path.expanduser(s)),
                        nargs=1,
                        help='Presentation HTML file generated by Hieroglyph',
    )

    return parser


def main():

    parser = _get_arg_parser()
    args = parser.parse_args()

    if args.firefox is None:
        args.firefox = cascajal.profile.find_firefox()

    if args.firefox is None:
        print("Unable to locate Firefox; try running with --firefox.")
        sys.exit(1)

    with cascajal.profile.Profile(vars(args)) as profile:

        cmdline = [
            args.firefox,
            '-no-remote',
            '-profile',
            profile.location,
            'file://%s' % (args.input_file[0],),
        ]

        print("Preparing to run Firefox; when Firefox starts, "
              "press CTRL-P to generate your PDF."
        )

        print args
        subprocess.call(cmdline)
