from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util

__name_att__ = None;

def _export(objid, parentrespath, name = ""):
  Util.pushPathElement('NameSpaceBinding')


  if parentrespath == "/":
    parentrespath = "";
  respath = "%(parentrespath)s/%(name)s" % { 'parentrespath':parentrespath, 'name':name }
  if not respath.startswith("/"):
    respath = "/" + respath;

  exportedObject = JSONObject();
  exportedObject.put("name", name);
  exportedObject.put("path", respath);
  exportedObject.put("teamMappings", JSONArray());
  exportedObject.put("inheritTeam", "true");
  exportedObject.put("description", "Discovered WebSphereNameSpaceBinding");
  exportedObject.put("roleName", "WebSphereNameSpaceBinding");

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.namespacebinding.name", objid, "name","NameSpaceBinding");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.namespacebinding.nameinnamespace", objid, "nameInNameSpace","NameSpaceBinding");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('NameSpaceBinding');
  return result;



def create(parentid, jsonobject):
  Util.pushPathElement('NameSpaceBinding')
  if not jsonobject.has("roleProperties"):
    raise Exception("NameSpaceBinding resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.namespacebinding.name", None));
  Util.addIfNotNone(properties, "nameInNameSpace", roleProperties.optString("websphere.namespacebinding.nameinnamespace", None));
  print "Creating NameSpaceBinding with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("NameSpaceBinding", parentid, properties);
  Util.popPathElement('NameSpaceBinding');

def update(objid,jsonobject):
  Util.pushPathElement('NameSpaceBinding')
  if not jsonobject.has("roleProperties"):
    raise Exception("NameSpaceBinding resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.namespacebinding.name", None), "name","NameSpaceBinding");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.namespacebinding.nameinnamespace", None), "nameInNameSpace","NameSpaceBinding");
  if len(atts) != 0:
    print "Modifying NameSpaceBinding with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

    Util.modify(objid, atts);
  else:   
    print "NameSpaceBinding configuration up to date.";

  Util.popPathElement('NameSpaceBinding');
