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

__name_att__ = "websphere.coregroupaccesspointref.name"

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

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

  roleProperties = JSONObject();

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



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

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

  name = roleProperties.getString("websphere.coregroupaccesspointref.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 CoreGroupAccessPoint on.");

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

  # we know this is either TunnelAccessPointGroup or AccessPointGroup, both of which are directly applicable
  parentType = Util.getObjectType(parentid);
  Util.pushPathElement(parentType);
  Util.modify(parentid, [['coreGroupAccessPointRefs', childid]]);
  Util.popPathElement(parentType);
