#!python

"""TasTopo - Generate printable topographic maps from TheList mapping service

Usage: tastopo generate [options] <location>

Options:
    -h --help            - Show this help message
    --version            - Show version information
    --scale <ratio>      - Specify the scale of the printed map [default: 25000]
    --zoom <offset>      - Increase or decrease the size of map details [default: 0]
    --translate <x>,<y>  - Shift the centre of the map a distance in metres [default: 0,0]
    --title <text>       - Set the title on the map sheet, instead of the location name
    --paper <size>       - Specify the paper size for printing [default: A4]
    --portrait           - Orientate the map in portrait, rather than landscape
    --no-grid            - Disable the rendering of a scale grid on the map
    --format <type>      - The file format to export; either PDF or SVG [default: PDF]
    --out <filename>     - Override the default export file naming

Map location
    The <location> argument is used to specify the centre of the map. This argument
    can take the form of a place name or a geo URI. Examples:
    - 'South East Cape'
    - 'geo:-43.643611,146.8275'
"""

from typing import cast

from docopt import docopt, DocoptExit

try:
    from src import tastopo
except ModuleNotFoundError:
    import tastopo


__version__ = '1.2.0'


if __name__ == '__main__':
    version = f'v{__version__}'
    try:
        args = docopt(__doc__, version=f'TasTopo {version}')
    except DocoptExit:
        args = docopt(__doc__ + '\n    --debug')

    try:
        tastopo.validate(args)

        translate = cast(tuple[int, int], tuple([-1 * int(x) for x in args['--translate'].split(',')]))
        location = tastopo.Location(args['<location>'], translate)

        sheet = tastopo.Sheet(args['--paper'], args['--portrait'])
        image = tastopo.Image(location, sheet, args['--scale'], args['--zoom'])

        layout = tastopo.Layout(sheet, location, image, args['--title'])
        layout.grid = not args['--no-grid']
        layout.details['version'] = version
        svg = layout.compose()

        filename = args['--out'] or f'TasTopo - {tastopo.clean_filename(layout.title)}'
        tastopo.export_map(svg, args['--format'], filename)

    except Exception as error:
        if args.get('--debug'):
            raise
        print(error)
        exit(1)
