# -*- coding: utf-8 -*-

import logging
from math import floor

from pyramid.view import view_config
from pyramid.httpexceptions import HTTPInternalServerError

from c2cgeoportal.lib.raster.georaster import GeoRaster
from c2cgeoportal.lib.config import cleanup_json

log = logging.getLogger(__name__)


class Raster(object):

    # cache of GeoRaster instances in function of the layer name
    _rasters = {}

    def __init__(self, request):
        self.request = request
        self.rasters = cleanup_json(self.request.registry.settings['raster'])

    @view_config(route_name='raster', renderer='json')
    def raster(self):
        lon = float(self.request.params['lon'])
        lat = float(self.request.params['lat'])
        if 'layers' in self.request.params:
            rasters = {}
            layers = self.request.params['layers'].split(',')
            for layer in layers:
                rasters[layer] = self.rasters[layer]
        else:
            rasters = self.rasters

        result = {}
        for ref in rasters.keys():
            result[ref] = self._get_raster_value(
                    rasters[ref], ref, lon, lat)

        return result

    def _get_raster_value(self, layer, ref, lon, lat):
        if ref in self._rasters:
            raster = self._rasters[ref]
        elif layer['type'] == 'shp_index':
            raster = GeoRaster(layer['file'])
        else:
            raise HTTPInternalServerError("Bad raster type '%s' for raster layer '%s'" \
                    % (layer['type'], ref))

        result = raster.get_value(lon, lat)
        if 'round' in layer:
            result = self._round(result, layer['round'])
        elif result:
            result = str(result)

        return result

    def _round(self, value, round_to):
        if value != None:
            value = round(value / round_to) * round_to
            if (round_to == floor(round_to)):
                return str(int(value))
            else:
                return str(value)
        else:
            return None

@@ -55,16 +55,44 @@
 rt floor
+%0Afrom decimal import Decimal
 %0A%0Afrom p
@@ -180,17 +180,57 @@
 verError
-%0A
+, HTTPNotFound%0A%0Aimport simplejson as json
 %0Afrom c2
@@ -971,44 +971,181 @@
     
-rasters%5Blayer%5D = self.rasters%5Blayer%5D
+if layer in self.rasters:%0A                    rasters%5Blayer%5D = self.rasters%5Blayer%5D%0A                else:%0A                    raise HTTPNotFound(%22Layer %25s not found%22 %25 layer)
 %0A   
@@ -1353,38 +1353,83 @@
 %0A        return 
-result
+Response(body=json.dumps(result, use_decimal=True))
 %0A%0A    def _get_r
@@ -1928,16 +1928,24 @@
 f result
+ != None
 :%0A      
@@ -1959,16 +1959,24 @@
 esult = 
+Decimal(
 str(resu
@@ -1978,16 +1978,17 @@
 (result)
+)
 %0A%0A      
@@ -2085,186 +2085,66 @@
     
-value = round(value / round_to) * round_to%0A            if (round_to == floor(round_to)):%0A                return str(int(value))%0A            else:%0A                return str(value
+return Decimal(str(value)).quantize(Decimal(str(round_to))
 )%0A  

use decimal instance of string