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

__name_att__ = "websphere.accesspointgroupref.name"

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

  if name == "":
    name = Util.getRequiredAttribute(objid, "name", "AccessPointGroup");
  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 WebSphereAccessPointGroupRef");
  exportedObject.put("roleName", "WebSphereAccessPointGroupRef");

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.accesspointgroupref.name", objid, "name","AccessPointGroup");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('AccessPointGroupRef');
  return result;



def doImport(containmentpath, roleName, jsonobject):
  if not jsonobject.has("roleProperties"):
    raise Exception("AccessPointGroupRef resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.accesspointgroupref.name"):
    raise Exception("Resource role properties does not contain websphere.accesspointgroupref.name!");

  name = roleProperties.getString("websphere.accesspointgroupref.name");

  #Parent is the object that we actually need to specify the reference on.
  index = containmentpath.rindex('/',0,len(containmentpath)-2)+1;
  parentconpath = containmentpath[0:index];
  parentid = Util.getid(parentconpath);
  if parentid == None or len(parentid) == 0:
    raise Exception("Parent does not exist to create AccessPointGroup on.");

  childid = Util.getid("/CoreGroupBridgeSettings:/AccessPointGroup:%s/" % name, ['AccessPointGroup']);
  if childid is None or len(childid) < 1:
    raise Exception("Cound not find AccessPointGroup with name %s specified by refernece!" % name);

  #we know the type must be AccessPointGroup or coreGroupAccessPoint, both of which are directly applicable
  parentType = Util.getObjectType(parentid);
  Util.pushPathElement(parentType);
  Util.modify(parentid, [['AccessPointGroup', childid]]);
  Util.popPathElement(parentType);
