#!/usr/bin/env python
"""A simple converter from SVG to PDF.

For further information please check the file README.txt!
"""

import sys
import argparse
import textwrap
from datetime import datetime
from os.path import dirname, basename, splitext, exists

from reportlab.graphics import renderPDF

from svglib import svglib


def svg2pdf(path, outputPat=None):
    "Convert an SVG file to a PDF one."

    # derive output filename from output pattern
    file_info = {
        'dirname': dirname(path) or '.',
        'basename': basename(path),
        'base': basename(splitext(path)[0]),
        'ext': splitext(path)[1],
        'now': datetime.now(),
        'format': 'pdf'
    }
    out_pattern = outputPat or '%(dirname)s/%(base)s.%(format)s'
    # allow classic %%(name)s notation
    out_path = out_pattern % file_info
    # allow also newer {name} notation
    out_path = out_path.format(**file_info)

    # generate a drawing from the SVG file
    try:
        drawing = svglib.svg2rlg(path)
    except:
        print('Rendering failed.')
        raise

    # save converted file
    if drawing:
        renderPDF.drawToFile(drawing, out_path, showBoundary=0)


# command-line usage stuff

def _main():
    ext = 'pdf'
    ext_caps = ext.upper()
    args = dict(
        prog=basename(sys.argv[0]),
        version=svglib.__version__,
        author=svglib.__author__,
        license=svglib.__license__,
        copyleft_year=svglib.__date__[:svglib.__date__.find('-')],
        ts_pattern="{{dirname}}/out-"\
                   "{{now.hour}}-{{now.minute}}-{{now.second}}-"\
                   "%(base)s",
        ext=ext,
        ext_caps=ext_caps
    )
    args['ts_pattern'] += ('.%s' % args['ext'])
    desc = '{prog} v. {version}\n'.format(**args)
    desc += 'A converter from SVG to {} (via ReportLab Graphics)\n'.format(ext_caps)
    epilog = textwrap.dedent('''\
        examples:
          # convert path/file.svg to path/file.{ext}
          {prog} path/file.svg

          # convert file1.svg to file1.{ext} and file2.svgz to file2.{ext}
          {prog} file1.svg file2.svgz

          # convert file.svg to out.{ext}
          {prog} -o out.{ext} file.svg

          # convert all SVG files in path/ to PDF files with names like:
          # path/file1.svg -> file1.{ext}
          {prog} -o "%(base)s.{ext}" path/file*.svg

          # like before but with timestamp in the PDF files:
          # path/file1.svg -> path/out-12-58-36-file1.{ext}
          {prog} -o {ts_pattern} path/file*.svg

        issues/pull requests:
            https://github.com/deeplook/svglib

        Copyleft by {author}, 2008-{copyleft_year} ({license}):
            https://www.gnu.org/licenses/lgpl-3.0.html'''.format(**args))
    p = argparse.ArgumentParser(
        description=desc,
        epilog=epilog,
        formatter_class=argparse.RawDescriptionHelpFormatter
    )

    p.add_argument('-v', '--version',
        help='Print version number and exit.', 
        action='store_true')

    p.add_argument('-o', '--output',
        metavar='PATH_PAT',
        help='Set output path (incl. the placeholders: dirname, basename,'
             'base, ext, now) in both, %%(name)s and {name} notations.'
    )

    p.add_argument('input',
        metavar='PATH',
        nargs='*',
        help='Input SVG file path with extension .svg or .svgz.')

    args = p.parse_args()

    if args.version:
        print(svglib.__version__)
        sys.exit()

    if not args.input:
        p.print_usage()
        sys.exit()

    paths = [a for a in args.input if exists(a)]
    for path in paths:
        svg2pdf(path, outputPat=args.output)


if __name__ == '__main__':
    _main()
