# ===========================================================================
# Copyright (C) 2006 Ancient World Mapping Center
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
# 
# About Pleiades
# --------------
#
# Pleiades is an international research network and associated web portal and
# content management system devoted to the study of ancient geography. 
#
# See http://icon.stoa.org/trac/pleiades/wiki.
#
# Funding for the creation of this software was provided by a grant from the 
# U.S. National Endowment for the Humanities (http://www.neh.gov).
# ===========================================================================

from OFS.SimpleItem import SimpleItem
from OFS.PropertyManager import PropertyManager
from AccessControl import ClassSecurityInfo
from Products.CMFCore.utils import UniqueObject, getToolByName

from config import product_name, unique_id
from config import view_permission, list_members_permission

from Products.PageTemplates.PageTemplateFile import PageTemplateFile

from geopy.geocoders import Google

from Products.PleiadesGeocoder.interfaces import IGeoreferenceable


class Geocoder(UniqueObject, PropertyManager, SimpleItem):
    
    """A proxy for geocoders using geopy.
    """
    meta_type = product_name
    id = unique_id
    
    security = ClassSecurityInfo()
    
    def __init__(self, **kwargs):
        """Create a new instance.
        """
        self._g = Google(resource='maps')

    security.declareProtected(view_permission, 'geocode')
    def geocode(self, location):
        """Return a one or more results matching a Plone location.

        Parameters
        ----------
        location : string
            A geo-codeable location string such as:
          
            "London, England"

        """
            
        # Get results
        records = []
        results = [x for x in self._g.geocode(location, exactly_one=False)]
        for result in results:
            r = {}
            r['place'] = result[0]
            r['lat'] = result[1][0]
            r['lon'] = result[1][1]
            records.append(r)
        return records
       
    security.declareProtected(view_permission, 'geocodeForm')
    geocodeForm = PageTemplateFile('www/geocode.pt', globals())

    manage_options = (
        {'label': 'Geocode', 'action': 'geocodeForm'},
        ) + PropertyManager.manage_options + SimpleItem.manage_options

    security.declareProtected(view_permission, 'isGeoreferenceable')
    def isGeoreferenceable(self, object):
        if IGeoreferenceable.providedBy(object):
            return True
        else:   
            return False


class GeocoderError(Exception):
    pass

