#!/usr/local/bin/python2.6
# _*_ coding: UTF-8 _*_

"""Add a grid on top of all pages of a PDF document."""

import re
import sys
import getopt
import os.path

from reportlab.lib.units import mm, cm, inch
from reportlab.lib import colors

from pdfgrid import grid


__version__ = "0.2.0"
__license__ = "GPL 3"
__author__ = "Dinu Gherman"
__date__ = "2009-06-07"


# command-line usage stuff

def _showVersion():
    "Print version message and terminate."

    prog = os.path.basename(sys.argv[0])
    print "%s %s" % (prog, __version__)
    sys.exit()


def _showUsage():
    "Print usage message and terminate."

    prog = os.path.basename(sys.argv[0])
    copyrightYear = __date__[:__date__.find("-")]
    args = (prog, __version__, __author__, copyrightYear, __license__)
    print "%s v. %s, Copyleft by %s, %s (%s)" % args 
    print "Add a grid on top of all pages of a PDF document."
    print "USAGE: %s [options] file1 [file2...]" % prog
    print """\
OPTIONS:
  -h --help          Print this usage message and exits.
  -v --version       Print version number and exits.
  -o --output FILE   Set output path (incl. some patterns).
  --origin X,Y       Set origin to given coordinates in points (default: "0,0").
  --gridsize SIZE    Set grid size to given area (default: "A4").
  --styles VALUES    Set styles (grid step, line width, colour), seprated by
                     semikola (default: "1*cm,0.1,colors.black").

EXAMPLES:
  %(prog)s file.pdf                       # default 1 cm grid 
  %(prog)s --origin "2*cm,3*cm" file.pdf  # origin at x,y=2,3 cm
  %(prog)s --styles "2*cm,1,red" file.pdf # grid step, line width, colour
  %(prog)s --styles "5*mm,0,colors.blue;50*mm,1,colors.red" file.pdf

COPYLEFT:
  see http://www.gnu.org/copyleft/gpl.html
""" % {"prog": prog}

    sys.exit()


def _main():
    "Main for command-line usage."

    try:
        longOpts = "help version output= origin= styles=".split()
        opts, args = getopt.getopt(sys.argv[1:], "hvo:", longOpts)
    except getopt.GetoptError:
        print "ERROR"
        _showUsage()
    
    stopOptions = "-v --version -h --help"
    stopOptions = [key for (key, val) in opts if key in stopOptions]
    if len(args) == 0 and len(stopOptions) == 0:
        _showUsage()

    outputPat = None
    origin = None
    styles = None
    for key, val in opts:
        if key in ("-h", "--help"):
            _showUsage()
        elif key in ("-v", "--version"):
            _showVersion()
        elif key in ("-o", "--output"):
            outputPat = val
        elif key == "--origin":
            origin = eval(val)
        elif key == "--styles":
            styles = val.split(";")
            styles = [eval(s) for s in styles]

    # determine paths of input files
    paths = [a for a in args if os.path.exists(a)]

    for path in paths:
        grid(path, origin=origin, styles=styles, outputPat=outputPat)


if __name__ == '__main__':    
    _main()
