

#
# ============================================
#
#  Lector de los metadatos de GPS de las imagenes
#
import os

from gvsig.uselib import use_jar

use_jar(os.path.join(os.path.dirname(__file__),"libs","metadata-extractor-2.8.1.jar"))
use_jar(os.path.join(os.path.dirname(__file__),"libs","xmpcore-5.1.2.jar"))

from com.drew.imaging import ImageMetadataReader


class ImageGPSMetadata:
  def __init__(self,pathname=None):
    self.load(pathname)

  def load(self, pathname):
    self.__pathname = pathname
    self.__values = dict()
    if pathname != None:
      metadata = ImageMetadataReader.readMetadata(pathname)
      for directory in metadata.getDirectories():
        if directory.getName() == "GPS":
          for tag in directory.getTags():
            self.__values[tag.getTagName().strip()] = tag.getDescription().strip()

  def getLatitude(self, defaultValue=None):
    return self.__values.get("GPS Latitude",defaultValue)

  def getLatitudeRef(self, defaultValue=None):
    return self.__values.get("GPS Latitude Ref",defaultValue)

  def getLongitude(self, defaultValue=None):
    return self.__values.get("GPS Longitude",defaultValue)

  def getLongitudeRef(self, defaultValue=None):
    return self.__values.get("GPS Longitude Ref",defaultValue)

  def getAltitude(self, defaultValue=None):
    return self.__values.get("GPS Altitude",defaultValue)

  def getAltitudeRef(self, defaultValue=None):
    return self.__values.get("GPS Altitude Ref",defaultValue)

  def getDatum(self, defaultValue=None):
    return self.__values.get("GPS Map Datum",defaultValue)

  def getDate(self, defaultValue=None):
    return self.__values.get("GPS Date Stamp",defaultValue)

  def getTime(self, defaultValue=None):
    return self.__values.get("GPS Time-Stam",defaultValue)

  def hasPosition(self):
    if self.getLatitude() == None or self.getLatitudeRef() == None or self.getLongitude() == None or self.getLongitudeRef() == None:
      return False
    return True

  def getPoint(self):
    import re

    def getFloat(s):
      return float(s.replace(",","."))

    if not self.hasPosition():
      return None

    latitud_ref = self.getLatitudeRef().strip().lower()
    longitud_ref = self.getLongitudeRef().strip().lower()

    m = re.search("[ ]*([0-9,]+).* ([0-9,]+).* ([0-9,]+)", self.getLatitude())
    la = getFloat(m.group(1)) + getFloat(m.group(2))/60 + getFloat(m.group(3))/3600
    if latitud_ref == "S":
      la = -la

    m = re.search("[ ]*([0-9,]+).* ([0-9,]+).* ([0-9,]+)", self.getLongitude())
    lo = getFloat(m.group(1)) + getFloat(m.group(2))/60 + getFloat(m.group(3))/3600
    if longitud_ref in ("O", "W"):
      lo = -lo

    from org.gvsig.fmap.geom import GeometryLocator
    from org.gvsig.fmap.geom import Geometry

    geomManager = GeometryLocator.getGeometryManager()
    point = geomManager.createPoint(lo,la, Geometry.SUBTYPES.GEOM2D)
    return point
