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

__name_att__ = "websphere.peeraccesspoint.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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

def _export(objid, parentrespath):
  Util.pushPathElement('PeerAccessPoint')

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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.peeraccesspoint.cell", objid, "cell","PeerAccessPoint");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.peeraccesspoint.coregroupaccesspoint", objid, "coreGroupAccessPoint","PeerAccessPoint");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.peeraccesspoint.name", objid, "name","PeerAccessPoint");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.peeraccesspoint.coregroup", objid, "coreGroup","PeerAccessPoint");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.peeraccesspoint.cellaccesspermission", objid, "cellAccessPermission","PeerAccessPoint");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"PeerAccessPoint");
  i = 0;
  j = 0;
  endpoints = Util.parseConfigIdListAttribute(objid, 'peerEndPoints',"PeerAccessPoint");
  for endpoint in endpoints:
    if len(endpoint) > 0:
      if endpoint.find("#EndPoint_") != -1:
        returndict = Util.createTypeFolder(respath, "EndPoint", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        Util.addAllFromExport(extraObjects, EndPoint._export(endpoint, currespath, "EndPoint%s" % i));
        i = i + 1;
      elif endpoint.find("#OverlayEndpoint_") != -1:
        returndict = Util.createTypeFolder(respath, "OverlayEndpoint", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        Util.addAllFromExport(extraObjects, OverlayEndpoint._export(endpoint, currespath, "OverlayEndpoint%s" % j));
        j = j + 1;

  proxy = Util.getOptionalAttribute(objid, 'proxyPeerAccessPointRef', 'PeerAccessPoint');
  if proxy is not None and len(proxy) > 0:
    returndict = Util.createTypeFolder(respath, "Proxy Peer Access Point", typeFolders, 1);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, PeerAccessPointRef._export(proxy, currespath));
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('PeerAccessPoint');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.peeraccesspoint.name"):
    raise Exception("Resource role properties does not contain websphere.peeraccesspoint.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 PeerAccessPoint on.");
    objid = create(parentid, jsonobject);
  else:
    update(objid,jsonobject);
  return objid;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "cell", roleProperties.optString("websphere.peeraccesspoint.cell", None));
  Util.addIfNotNone(properties, "coreGroupAccessPoint", roleProperties.optString("websphere.peeraccesspoint.coregroupaccesspoint", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.peeraccesspoint.name", None));
  Util.addIfNotNone(properties, "coreGroup", roleProperties.optString("websphere.peeraccesspoint.coregroup", None));
  Util.addIfNotNone(properties, "cellAccessPermission", roleProperties.optString("websphere.peeraccesspoint.cellaccesspermission", None));

  print "Creating PeerAccessPoint with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("PeerAccessPoint", parentid, properties);

  #unset proxyPeerAccessPointRef. we will expect a subresource to handle this if necessary.
  Util.unsetAttribute(objid, "proxyPeerAccessPointRef", "PeerAccessPoint");

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereEndPoint":
        EndPoint.create(objid, curjsonobject, 'peerEndPoints');
      elif currole == "WebSphereOverlayEndpoint":
        OverlayEndpoint.create(objid, curjsonobject, 'peerEndPoints');
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('PeerAccessPoint');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.peeraccesspoint.cell", None), "cell","PeerAccessPoint");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.peeraccesspoint.coregroupaccesspoint", None), "coreGroupAccessPoint","PeerAccessPoint");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.peeraccesspoint.name", None), "name","PeerAccessPoint");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.peeraccesspoint.coregroup", None), "coreGroup","PeerAccessPoint");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.peeraccesspoint.cellaccesspermission", None), "cellAccessPermission","PeerAccessPoint");

  if len(atts) != 0:
    print "Modifying PeerAccessPoint with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  #unset proxyPeerAccessPointRef. we will expect a subresource to handle this if necessary.
  Util.unsetAttribute(objid, "proxyPeerAccessPointRef", "PeerAccessPoint");

  endpoints = Util.parseConfigIdListAttribute(objid, 'peerEndPoints',"PeerAccessPoint");
  for endpoint in endpoints:
    Util.remove(endpoint);

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereEndPoint":
        EndPoint.create(objid, curjsonobject, 'peerEndPoints');
      elif currole == "WebSphereOverlayEndpoint":
        OverlayEndpoint.create(objid, curjsonobject, 'peerEndPoints');
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('PeerAccessPoint');
