#
# REMEMBER
# latitude  : phi
# longitude : lam
#
import os
import yaml
import urllib

try:
  CACHE_FILE = os.environ['RD2ETRS_CACHE']
except KeyError:
  CACHE_FILE = os.path.join(os.environ['HOME'],'.rd2etrs.yaml')
coordinates = None

def get_yaml(gfile):
  """ Get configuration yaml for 'item'"""
  f = open(gfile, 'r')
  datadump = yaml.load(f)
  return datadump

def write_yaml(gfile, datadump):
  """ Write configuration yaml for 'item'"""
  try:
    f = open(gfile, 'w')
    f.write(yaml.dump(datadump, default_flow_style=False))
    f.close()
  except IOError:
    pass

def etrs2rd(lam, phi):
  """ Convert etrs to rd """
  
  item['lam'] = lam
  item['phi'] = phi
  item['func'] = 'etrs2rd'
  url = 'http://vanderzwet.net/rdnap/%(func)s/%(xrd)s/%(yrd)s/0/' % item

  f = urllib.urlopen(url)
  raw = f.read()
  
  rdnap_x,rdnap_y,rdnap_h = raw.split('/')
  return (rdnap_x, rdnap_y)



def rd2etrs(xrd, yrd, hnap=0.0):
  """ 
  Convert rd to etrs 
  JavaScript Version: https://rdinfo.kadaster.nl/rd/transformator.html
  """
  # Get cache is exists
  global coordinates
  if coordinates == None:
    try: 
      coordinates = get_yaml(CACHE_FILE)
    except (IOError,AttributeError):
      coordinates = dict()
      pass

  # Check if item in cache
  xrd = float(str(xrd))
  yrd = float(str(yrd))
  if coordinates.has_key((xrd, yrd)):
    return coordinates[(xrd, yrd)]

  # Get new coordinate
  item = dict()
  item['xrd'] = xrd
  item['yrd'] = yrd
  item['hnap'] = hnap
  item['func'] = 'rd2etrs'
  url = 'http://vanderzwet.net/rdnap/%(func)s/%(xrd)s/%(yrd)s/%(hnap)s/' % item
  print "### Not in Cache, Fetching coordinate %s, %s from %s" % (xrd, yrd, url) 
  f = urllib.urlopen(url)
  raw = f.read()
  
  # Coordinates returned in 'odd' order
  phi,lam,h = raw.split('/')
  coordinates[(xrd, yrd)] = (lam, phi)
  write_yaml(CACHE_FILE, coordinates)
  return (lam, phi)
