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

__name_att__ = 'websphere.tunnelpeeraccesspoint.name';

def export(objid, parentcontainmentpath, parentrespath):

  name = Util.getRequiredAttribute(objid, "name", 'TunnelPeerAccessPoint');

  containmentpath = "%(parentconpath)sTunnelPeerAccessPoint:%(name)s/" % {'parentconpath':parentcontainmentpath, 'name':name }
  if not containmentpath.startswith("/"):
    containmentpath = "/" + containmentpath;

  dict = _export(objid, parentrespath, name);
  dict['conpath'] = containmentpath;
  return dict

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tunnelpeeraccesspoint.name", objid, "name","TunnelPeerAccessPoint");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tunnelpeeraccesspoint.retrydelay", objid, "retryDelay","TunnelPeerAccessPoint");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tunnelpeeraccesspoint.usessl", objid, "useSSL","TunnelPeerAccessPoint");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tunnelpeeraccesspoint.sslconfigalias", objid, "sslConfigAlias","TunnelPeerAccessPoint");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tunnelpeeraccesspoint.cellname", objid, "cellName","TunnelPeerAccessPoint");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.tunnelpeeraccesspoint.cellaccesspermission", objid, "cellAccessPermission","TunnelPeerAccessPoint");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"TunnelPeerAccessPoint");
  i = 0;
  peergroups = Util.parseConfigIdListAttribute(objid, 'peerCoreGroups', 'TunnelPeerAccessPoint');
  for peergroup in peergroups:
    if len(peergroup) > 0:
      returndict = Util.createTypeFolder(respath, 'PeerCoreGroup', typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, PeerCoreGroup._export(peergroup, currespath, "PeerCoreGroup%s" % i));
      i = i + 1;
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('TunnelPeerAccessPoint');
  return result;

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

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

  objid = Util.getid(containmentpath);
  if objid == None or len(objid) == 0:
    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 TunnelPeerAccessPoint on.");
    objid = create(parentid, jsonobject);
  else:
    update(objid,jsonobject);
  return objid;


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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.tunnelpeeraccesspoint.name", None));
  Util.addIfNotNone(properties, "retryDelay", roleProperties.optString("websphere.tunnelpeeraccesspoint.retrydelay", None));
  Util.addIfNotNone(properties, "useSSL", roleProperties.optString("websphere.tunnelpeeraccesspoint.usessl", None));
  Util.addIfNotNone(properties, "sslConfigAlias", roleProperties.optString("websphere.tunnelpeeraccesspoint.sslconfigalias", None));
  Util.addIfNotNone(properties, "cellName", roleProperties.optString("websphere.tunnelpeeraccesspoint.cellname", None));
  Util.addIfNotNone(properties, "cellAccessPermission", roleProperties.optString("websphere.tunnelpeeraccesspoint.cellaccesspermission", None));
  print "Creating TunnelPeerAccessPoint with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("TunnelPeerAccessPoint", parentid, properties);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSpherePeerCoreGroup":
        PeerCoreGroup.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('TunnelPeerAccessPoint');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tunnelpeeraccesspoint.name", None), "name","TunnelPeerAccessPoint");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tunnelpeeraccesspoint.retrydelay", None), "retryDelay","TunnelPeerAccessPoint");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tunnelpeeraccesspoint.usessl", None), "useSSL","TunnelPeerAccessPoint");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tunnelpeeraccesspoint.sslconfigalias", None), "sslConfigAlias","TunnelPeerAccessPoint");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tunnelpeeraccesspoint.cellname", None), "cellName","TunnelPeerAccessPoint");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.tunnelpeeraccesspoint.cellaccesspermission", None), "cellAccessPermission","TunnelPeerAccessPoint");
  if len(atts) != 0:
    print "Modifying TunnelPeerAccessPoint with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  
  peergroups = Util.parseConfigIdListAttribute(objid, 'peerCoreGroups', 'TunnelPeerAccessPoint');
  for peergroup in peergroups:
    Util.remove(peergroup);

  Property.removeProperties(objid, 'properties',"TunnelPeerAccessPoint");

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSpherePeerCoreGroup":
        PeerCoreGroup.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('TunnelPeerAccessPoint');
