import os
import sys

import simplejson

from zope.event import notify

from Products.Five.browser import BrowserView

from Products.PleiadesGeocoder.interfaces import IGeoItemSimple
from Products.PleiadesGeocoder.geo import GeoreferencedEvent


class EditGeo(BrowserView):

    __name__ = 'edit_geo'

    def __call__(self):
        """Request parameters are 'type' and 'coordinates'."""
        request = self.request
        response = request.response
        try:
            gtype = request.form.get('type')
            coords = simplejson.loads(request.form.get('coordinates'))
            assert gtype in ['Point', 'LineString', 'Polygon']
            assert len(coords) > 0
        except:
            raise
            response.setStatus(400)
            return "Input geometry is not acceptable"

        g = IGeoItemSimple(self.context)
        g.setGeoInterface(gtype, coords)
        notify(GeoreferencedEvent(g))

        if request.get('HTTP_REFERER'):
            response.redirect(request.get('HTTP_REFERER').split('?')[0] + '?portal_status_message=Changes%20saved.')
        else:
            response.setStatus(200)
            return "Geometry edited successfully"


class EditGeoForm(BrowserView):

    __name__ = 'edit_geo_form'

    def __init__(self, context, request):
        self.context = context
        self.request = request
        self.geo = IGeoItemSimple(self.context).__geo_interface__

    def name(self):
        return self.context.Title()
        
    def hasPoint(self):
        if self.geo['geometry']['type'] == 'Point':
            return 1
        else:
            return 0
        
    def hasLineString(self):
        if self.geo['geometry']['type'] == 'LineString':
            return 1
        else:
            return 0

    def hasPolygon(self):
        if self.geo['geometry']['type'] == 'Polygon':
            return 1
        else:
            return 0

    def coords_json(self):
        return simplejson.dumps(self.geo['geometry']['coordinates'])

    def json(self):
        return simplejson.dumps(self.geo)
        
    def action(self):
        return os.sep.join([self.context.absolute_url(), '@@edit_geo'])

    def coords_kml(self):
        if self.geo['geometry']['type'] == 'Point':
            coords = (self.geo['geometry']['coordinates'],)
        elif self.geo['geometry']['type'] == 'Polygon':
            coords = self.geo['geometry']['coordinates'][0]
        else:
            coords = self.geo['geometry']['coordinates']
        tuples = ('%f,%f,%f' % c for c in coords)
        return ' '.join(tuples)

