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

__name_att__ = "websphere.tunnelaccesspointgroupref.name"

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

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

  roleProperties = JSONObject();

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



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

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

  name = roleProperties.getString("websphere.tunnelaccesspointgroupref.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:/TunnelAccessPointGroup:%s/" % name, ['TunnelAccessPointGroup']);
  if childid is None or len(childid) < 1:
    raise Exception("Cound not find TunnelAccessPointGroup with name %s specified by refernece!" % name);

  #the only supported parent of tunnelAccessPointGroupRef is TunnelTemplate
  Util.pushPathElement("TunnelTemplate");
  Util.modify(parentid, [['tunnelAccessPointGroupRef', childid]]);
  Util.popPathElement("TunnelTemplate");
