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

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.peercoregroup.coregroup", objid, "coreGroup","PeerCoreGroup");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  i = 0;
  j = 0;
  endpoints = Util.parseConfigIdListAttribute(objid, 'endPoints',"PeerCoreGroup");
  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;
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('PeerCoreGroup');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "coreGroup", roleProperties.optString("websphere.peercoregroup.coregroup", None));
  print "Creating PeerCoreGroup with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("PeerCoreGroup", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereEndPoint":
        EndPoint.create(objid, curjsonobject, 'endPoints');
      elif currole == "WebSphereOverlayEndpoint":
        OverlayEndpoint.create(objid, curjsonobject, 'endPoints');
  Util.popPathElement('PeerCoreGroup');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.peercoregroup.coregroup", None), "coreGroup","PeerCoreGroup");
  if len(atts) != 0:
    print "Modifying PeerCoreGroup with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereEndPoint":
        EndPoint.create(objid, curjsonobject, 'endPoints');
      elif currole == "WebSphereOverlayEndpoint":
        OverlayEndpoint.create(objid, curjsonobject, 'endPoints');
  Util.popPathElement('PeerCoreGroup');
