#!/toc/home/edemaine/bin/python-beta

"""YAML -> GPX converter

Specifically for map data and GPS units.

Distributed according to the MIT License; see also
        http://www.opensource.org/licenses/mit-license.php

Copyright (c) 1997-2006 Erik D. Demaine

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

"""

import datetime, operator, optparse, os, sys
import yaml

def name2gpx (name):
  return name
#def name2gpx (name):
#  return name.replace (' ', '_')

def py2gpx_waypoint (data, indent):
  s = indent + '<wpt lat="%s" lon="%s">\n' % \
               (data['latitude'], data['longitude'])
  s += indent + '  <name>%s</name>\n' % name2gpx (data['title'])
  if 'address' in data: s += indent + '  <dsc>%s</dsc>\n' % data['address']
  if 'lines' in data: s += indent + '  <type>%s</type>\n' % data['lines']
  if 'url' in data: s += indent + gpx_link (data['url'].replace ('&', '&amp;'), indent = '  ')
  s += indent + '</wpt>\n'
  return s

def py2gpx_track (data, indent):
  s = indent + '<trk>\n'
  s += indent + '  <name>%s</name>\n' % name2gpx (data['title'])
  s += indent + '  <trkseg>\n'
  for station in data['stations']:
    s += indent + '    <trkpt lat="%s" lon="%s"/>\n' % \
                  (station['latitude'], station['longitude'])
  s += indent + '  </trkseg>\n'
  s += indent + '</trk>\n'
  return s

def py2gpx_nohead (data, indent = '', seen = None):
  if seen is None: seen = set ()
  if type (data) == list:
    return ''.join (py2gpx_nohead (item, indent, seen) for item in data)
  elif 'stations' in data:
    return py2gpx_track (data, indent) + \
           py2gpx_nohead (data['stations'], indent, seen)
  elif 'latitude' in data and 'longitude' in data and 'title' in data:
    if id (data) in seen: return ''
    seen.add (id (data))
    return py2gpx_waypoint (data, indent)
  else:
    return ''

def merge_bounds (a, b):
  if a is None: return b
  if b is None: return a
  (minlat1, minlon1, maxlat1, maxlon1) = a
  (minlat2, minlon2, maxlat2, maxlon2) = b
  return (min (minlat1, minlat2), min (minlon1, minlon2),
          max (maxlat1, maxlat2), max (maxlon1, maxlon2))

def compute_bounds (data):
  assert type (data) in [list, dict]
  if type (data) == list:
    return reduce (merge_bounds, (compute_bounds (item) for item in data))
  elif 'stations' in data:
    return compute_bounds (data['stations'])
  elif 'latitude' in data and 'longitude' in data and 'title' in data:
    return (data['latitude'], data['longitude'],
            data['latitude'], data['longitude'])
  else:
    return None

class Now:
  @staticmethod
  def isoformat (*args):
    return datetime.datetime.now ().isoformat (*args)

def gpx_link (link, attr = 'link', indent = ''):
  if type (link) not in [tuple, list]: link = (link,)
  assert len (link) in [1,2,3]
  s = indent + '<%s href="%s"' % (attr, link[0])
  if len (link) == 1 or (len (link) == 2 and link[1] is None) \
                     or (len (link) == 3 and link[1] is link[2] is None):
    s += '/>\n'
  else:
    s += '>\n'
    if len (link) >= 2 and link[1] is not None:
      s += indent + '  <text>%s</text>\n' % link[1]
    if len (link) >= 3 and link[2] is not None:
      s += indent + '  <type>%s</type>\n' % link[2]
    s += indent + '</%s>\n' % attr
  return s

def gpx_header (creator = "Erik Demaine's YAML-to-GPX converter",
                name = None, desc = None,
                author_name = None, author_email = None, author_link = None,
                copyright_author = None, copyright_year = None,
                copyright_license = None,
                link = None, time = Now, keywords = None, bounds = None):
  s = '''\
<?xml version="1.0"?>
<gpx version="1.1"'''
  if creator is not None: s += ' creator="%s"' % creator
  s += '''
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://www.topografix.com/GPX/1/1"
 xsi:schemaLocation="http://www.topografix.com/GPX/1/1 http://www.topografix.com/GPX/1/1/gpx.xsd">
  <metadata>
'''
  if name is not None: s += '    <name>%s</name>\n' % name
  if desc is not None: s += '    <desc>%s</desc>\n' % desc
  if author_name is not None or author_email is not None or \
     author_link is not None:
    s += '    <author>\n'
    if author_name is not None: s += '      <name>%s</name>\n' % author_name
    if author_email is not None:
      id, domain = author_email.split ('@')
      s += '      <email id="%s" domain="%s"/>\n' % (id, domain)
    if author_link is not None: s += gpx_link (author_link, indent = '      ')
    s += '    </author>\n'
  if copyright_author is not None:
    s += '    <copyright author="%s"' % copyright_author
    if copyright_year is not None or copyright_license is not None:
      s += '>\n'
      if copyright_year is not None:
        s += '      <year>%s</year>\n' % copyright_year
      if copyright_license is not None:
        s += '      <license>%s</license>\n' % copyright_license
      s += '    </copyright>\n'
    else:
      s += '/>\n'
  if link is not None: s += gpx_link (link, indent = '    ')
  if time is not None: s += '    <time>%s</time>\n' % time.isoformat ()
  if keywords is not None: s += '    <keywords>%s</keywords>\n' % keywords
  if bounds is not None:
    s += '    <bounds minlat="%s" minlon="%s" maxlat="%s" maxlon="%s"/>\n' % \
         bounds
  s += '''\
  </metadata>
'''
  return s

def gpx_footer ():
  return '</gpx>\n'

def py2gpx (data, **args):
  if 'bounds' not in args:
    args['bounds'] = compute_bounds (data)
  return gpx_header (**args) + \
         py2gpx_nohead (data, indent = '  ') + \
         gpx_footer ()

def yaml2gpx (data, **args):
  return py2gpx (yaml.load (data), **args)

def yaml2gpx_file (input, output, **args):
  input = file (input, 'r')
  output = file (output, 'w')
  output.write (yaml2gpx (input.read (), **args))
  output.close ()
  input.close ()

optparser = optparse.OptionParser (
  usage = 'Usage: %prog [options] filename.yaml [filename.gpx]')
optparser.add_option ('-n', '--name', dest = 'name', help ='name of file')
optparser.add_option ('-a', '--author-name', dest = 'author_name',
                      help = 'author name')
optparser.add_option ('-e', '--author-email', dest = 'author_email',
                      help = 'author email')
optparser.add_option ('-p', '--author-link', dest = 'author_link',
                      help = 'author URI')
optparser.add_option ('-c', '--copyright-author', dest = 'copyright_author',
                      help = 'copyright author name')
optparser.add_option ('-y', '--copyright-year', dest = 'copyright_year',
                      help = 'copyright year')
optparser.add_option ('-l', '--copyright-license', dest = 'copyright_license',
                      help = 'copyright license URI')
optparser.add_option ('-u', '--link', dest = 'link', help = 'related URI')

def main ():
  options, args = optparser.parse_args ()
  if len (args) not in (1, 2):
    optparser.error ('incorrect number of arguments')
  input = args[0]
  if len (args) >= 2:
    output = args[1]
  else:
    output = os.path.splitext (input) [0] + '.gpx'
  yaml2gpx_file (input, output, **options.__dict__)

if __name__ == '__main__': main ()
