#!/usr/bin/env python
# -*- coding: utf-8 -*-
from gluon import *

from plugin_geotip.tools import getUUID
# from plugin_geotip.widgets import GeoJsonCollector
from geojson import FeatureCollection
from gluon.contrib import simplejson as json

if current.T is None:
    T = lambda v: v
else:
    T = current.T

class GeoJsonCollector(object):
 
    feature_attributes = dict(
#         properties = dict(
#             id = lambda r: r.id,
#             label = '',
#             name = lambda r: 
#         ),
        style = dict(
#             externalGraphic = URL('static', plugin_folder+'/images/my-marker-blue.png'),
            graphicHeight = 25,
            graphicWidth = 21,
            graphicXOffset = -12,
            graphicYOffset = -25,
            labelYOffset = -7,
            fontColor = "#084F72",
            fontWeight = "bold",
            labelOutlineColor = '#d9edf7',
            labelOutlineWidth = 3
        )
    )
 
    @classmethod
    def extract_feature(cls, row, fieldname='the_geom', table=None, escape=True, cid=None, actions=True):
         
        if table is None or table._format is None:
            format = lambda r: '%(id)s' % r
        elif isinstance(table._format, basestring) and '%' in table._format:
            format = lambda r: table._format % r
        elif callable(table._format):
            format = table._format
        else:
            assert False, "WARNING! It should never happen. Why it happens?"
 
        ccid = current.request.cid or cid
 
        def _get_btngrp():
            """
            <div class="btn-group">
              <button class="btn">Left</button>
              <button class="btn">Middle</button>
              <button class="btn">Right</button>
            </div>
            """
             
            def _get_btn(act, label, icon_class):
                url = URL('site', act, extension='html', args=(row.id, ), user_signature=True)
                 
                return A(I(_class=icon_class), ' ', T(label),
                    _title=T(label),
                    _class='button btn btn-default',
                    _href=url
                )
 
            return DIV(
                _get_btn("note", "Note", "icon magnifier glyphicon glyphicon-edit"),
                _get_btn("logrid", "Log", "icon magnifier glyphicon glyphicon-info-sign"),
#                 _get_btn("edit", "Edit", "icon pen icon-pencil glyphicon glyphicon-pencil"),
#                 _get_btn("delete", "Delete", "icon-trash"),
                _class="btn-group", **{'_data-toggle': "buttons"}
            ).xml()
 
        def _extract():
            el = row[fieldname] # if tablename is None else row[tablename][fieldname]
            if el is None:
                return None
            else:
                feature = el['features'][0]
                feature['id'] = row.id
                feature['properties'] = dict(
                    id = row.id,
                    name = format(row),
                    label = format(row),
                    title = format(row),
                )
                feature['properties']['actions'] = _get_btngrp().replace('"', '\\"') if escape else _get_btngrp()
                for key,attrs in cls.feature_attributes.iteritems():
                    for attrname, attr in attrs.iteritems():
                        if not key in feature:
                            feature[key] = {}
                        if callable(attr):
                            feature[key][attrname] = attr(row)
                        else:
                            feature[key][attrname] = attr
            return feature
 
        return _extract()
 
    @classmethod
    def extract_features(cls, rows, fieldname='the_geom', table=None, actions=True):
        def _fiter():
            for row in rows:
                feat = cls.extract_feature(row, fieldname, table, actions=actions)
                if not feat is None:
                    yield feat
        return FeatureCollection([f for f in _fiter()])

class Maprows(object):
    """ """
    
    map_defaults = {
        # Roma: lat: 41.9027835, lng: 12.4963655
#         '_data-map-center-lat': 41.9027835,
#         '_data-map-center-lng': 12.4963655,
        # Toscana lat: 43.7710513, lng: 11.2486208
        '_data-map-center-lat': 43.7710513,
        '_data-map-center-lng': 11.2486208,
        '_data-map-zoom': 10
    }

    @classmethod
    def draw(cls, rows, table=None, field_name="the_geom", map_type="DashboardMap"):
        map_uuid = 'map_%s' % getUUID()
        features = json.dumps(GeoJsonCollector.extract_features(rows, table=table, actions=False))
        encoded = XML(features)
        script = SCRIPT("""window.%(map_uuid)s = '%(encoded)s'; MapLoader();""" % locals(), _type="text/javascript")
        defaults = cls.map_defaults.copy()
        defaults.update(**{
           '_data-map': map_type,
           '_data-map-source': map_uuid,
#            '_data-map-update-url': URL(extension='json', args=(current.request.cid, )),
           '_data-map-geom-field-name': field_name,
#            '_data-form-name': map_uuid
        })
        popup = DIV(
            A("", _href="#", _id="popup-closer", _class="ol-popup-closer"),
            DIV("", _id="popup-content"),
            _id="popup", _class="ol-popup", _style="width: 210px;"
        )
        return DIV(popup,
            DIV(
                DIV(
                    _id=map_uuid, _class="geotipmap", _style="width: 100%",
                    **defaults
                ),
            _class="mapcontainer"),
           script
        )
