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

__name_att__ = None;

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


  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 WebSphereIIOPLayer");
  exportedObject.put("roleName", "WebSphereIIOPLayer");

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.iioplayer.useclaim", objid, "useClaim","IIOPLayer");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('IIOPLayer');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  Util.popPathElement('IIOPLayer');
