from django.shortcuts import HttpResponse
from geonode.layers.views import layer_detail
try:
    import simplejson as json
except:
    import json
import requests
from requests.auth import HTTPBasicAuth
from geonode.layers.views import _resolve_layer, _PERMISSION_MSG_MODIFY
from cartoview.log_handler import get_logger
logger = get_logger(__name__)


def convert_infinty(obj):
    if obj == float('inf') or obj == float('-inf'):
        return None
    else:
        return obj


def layer_config_json(request, layername):
    layer_details = layer_detail(
        request, layername)
    viewer = layer_details.context_data['viewer']
    layer = layer_details.context_data['resource']
    viewer = json.loads(viewer)
    try:
        layer.set_bounds_from_bbox(layer.bbox[0:4], layer.srid)
    except:
        layer.set_bounds_from_bbox(layer.bbox[0:4])
    center = [layer.center_x, layer.center_y]
    zoom = layer.zoom
    viewer['map']['center'] = center
    viewer['map']['zoom'] = zoom
    for l in viewer.get("map").get("layers"):
        if l.get('bbox', None):
            newBBox = []
            for x in l.get('bbox'):
                newBBox.append(convert_infinty(x))
            l.update({"bbox": newBBox})
    return HttpResponse(json.dumps(viewer),
                        content_type="application/json")


def get_featureType(self, workspace, store, lyr_name):
    gs_user, gs_password, gs_url = self.get_geoserver_credintials()
    target_url = "{}rest/workspaces/{}/datastores/{}/featuretypes/{}"\
        .format(
            gs_url, workspace, store, lyr_name)
    req = requests.get(target_url,
                       headers={'Accept': 'application/json'},
                       auth=HTTPBasicAuth(gs_user, gs_password))
    return json.loads(req.content)


def update_extent(self, request, typename):
    lyr = _resolve_layer(
        request,
        typename,
        'base.change_resourcebase',
        _PERMISSION_MSG_MODIFY)
    store = lyr.store
    workspace = lyr.workspace
    lyr_name = lyr.name
    feature_type = self.get_featureType(workspace, store, lyr_name)
    gs_user, gs_password, gs_url = self.get_geoserver_credintials()
    target_url = "{}rest/workspaces/{}/datastores/{}/featuretypes/{}"\
        .format(
            gs_url, workspace, store, lyr_name)
    req = requests.put(target_url+"?recalculate=nativebbox,latlonbbox",
                       json=feature_type,
                       headers={'Accept': 'application/json'},
                       auth=HTTPBasicAuth(gs_user, gs_password))
    if req.status_code == 200:
        new_feature_type = self.get_featureType(workspace, store, lyr_name)
        native_bbox = new_feature_type["featureType"]["nativeBoundingBox"]
        bbox = [native_bbox["minx"], native_bbox["maxx"],
                native_bbox["miny"], native_bbox["maxy"]]
        # srid = native_bbox["crs"]
        try:
            lyr.set_bounds_from_bbox(bbox, lyr.srid)
        except:
            lyr.set_bounds_from_bbox(bbox)
        lyr.save()
    return HttpResponse(json.dumps({"msg": "Success"}),
                        content_type="application/json")

@@ -156,16 +156,74 @@
 equests%0A
+from geonode.geoserver.helpers import ogc_server_settings%0A
 from req
@@ -254,16 +254,16 @@
 sicAuth%0A
-
 from geo
@@ -532,16 +532,235 @@
 n obj%0A%0A%0A
+def get_geoserver_credintials():%0A    gs_user = ogc_server_settings.credentials%5B0%5D%0A    gs_password = ogc_server_settings.credentials%5B1%5D%0A    gs_url = ogc_server_settings.LOCATION%0A    return gs_user, gs_password, gs_url%0A%0A%0A
 def laye
@@ -1617,22 +1617,16 @@
 ureType(
-self, 
 workspac
@@ -1673,37 +1673,32 @@
 sword, gs_url = 
-self.
 get_geoserver_cr
@@ -1698,34 +1698,32 @@
 rver_credintials
-()
 %0A    target_url 
@@ -2065,14 +2065,8 @@
 ent(
-self, 
 requ
@@ -2297,37 +2297,32 @@
  feature_type = 
-self.
 get_featureType(
@@ -2384,21 +2384,16 @@
 s_url = 
-self.
 get_geos
@@ -2409,18 +2409,16 @@
 dintials
-()
 %0A    tar
@@ -2819,16 +2819,16 @@
 == 200:%0A
+
         
@@ -2850,13 +2850,8 @@
 e = 
-self.
 get_

fix update_extent