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

__name_att__ = "websphere.peeraccesspointref.name"

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

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

  roleProperties = JSONObject();

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



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

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

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

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

  if parentid.find("#PeerAccessPoint_") != -1:
    Util.pushPathElement("PeerAccessPoint");
    Util.modify(parentid, [['proxyPeerAccessPointRef', childid]]);
    Util.popPathElement("PeerAccessPoint");
  elif parentid.find("#AccessPointGroup_") != -1:
    Util.pushPathElement("AccessPointGroup");
    Util.modify(parentid, [['peerAccessPointRefs', childid]]);
    Util.popPathElement("AccessPointGroup");
