from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from Liveness import Liveness
from CoreGroupServer import CoreGroupServer
from CoreGroupServerRef import CoreGroupServerRef
from utilities import Util
from Property import Property

__name_att__ = "websphere.coregroup.name"

def export(objid, parentcontainmentpath, parentrespath):

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

  containmentpath = "%(parentconpath)sCoreGroup:%(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('CoreGroup')

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.coregroup.name", objid, "name","CoreGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.coregroup.multicastgroupipstart", objid, "multiCastGroupIPStart","CoreGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.coregroup.transportmemorysize", objid, "transportMemorySize","CoreGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.coregroup.protocolversion", objid, "protocolVersion","CoreGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.coregroup.multicastgroupipend", objid, "multiCastGroupIPEnd","CoreGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.coregroup.numcoordinators", objid, "numCoordinators","CoreGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.coregroup.description", objid, "description","CoreGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.coregroup.transporttype", objid, "transportType","CoreGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.coregroup.multicastport", objid, "multiCastPort","CoreGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.coregroup.channelchainname", objid, "channelChainName","CoreGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.coregroup.coregroupuid", objid, "coreGroupUID","CoreGroup");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"CoreGroup");
  i = 0;
  liveness = Util.getOptionalAttribute(objid, 'liveness', 'CoreGroup');
  if liveness is not None and len(liveness) > 0:
    returndict = Util.createTypeFolder(respath, "Liveness", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, Liveness._export(liveness, currespath, 'Liveness'));
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('CoreGroup');
  return result;



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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.coregroup.name", None));
  Util.addIfNotNone(properties, "multiCastGroupIPStart", roleProperties.optString("websphere.coregroup.multicastgroupipstart", None));
  Util.addIfNotNone(properties, "transportMemorySize", roleProperties.optString("websphere.coregroup.transportmemorysize", None));
  Util.addIfNotNone(properties, "protocolVersion", roleProperties.optString("websphere.coregroup.protocolversion", None));
  Util.addIfNotNone(properties, "multiCastGroupIPEnd", roleProperties.optString("websphere.coregroup.multicastgroupipend", None));
  Util.addIfNotNone(properties, "numCoordinators", roleProperties.optString("websphere.coregroup.numcoordinators", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.coregroup.description", None));
  Util.addIfNotNone(properties, "transportType", roleProperties.optString("websphere.coregroup.transporttype", None));
  Util.addIfNotNone(properties, "multiCastPort", roleProperties.optString("websphere.coregroup.multicastport", None));
  Util.addIfNotNone(properties, "channelChainName", roleProperties.optString("websphere.coregroup.channelchainname", None));
  Util.addIfNotNone(properties, "coreGroupUID", roleProperties.optString("websphere.coregroup.coregroupuid", None));
  print "Creating CoreGroup with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("CoreGroup", parentid, properties);

  #remove liveness and recreate it
  liveness = Util.getOptionalAttribute(objid, 'liveness', 'CoreGroup');
  if liveness is not None and len(liveness) > 0:
    Util.remove(liveness);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereCoreGroupServer":
        CoreGroupServer.create(objid, curjsonobject);
      elif currole == "WebSphereCoreGroupServerRef":
        CoreGroupServerRef.create(objid, curjsonobject);
      elif currole == "WebSphereLiveness":
        Liveness.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('CoreGroup');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.coregroup.name", None), "name","CoreGroup");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.coregroup.multicastgroupipstart", None), "multiCastGroupIPStart","CoreGroup");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.coregroup.transportmemorysize", None), "transportMemorySize","CoreGroup");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.coregroup.protocolversion", None), "protocolVersion","CoreGroup");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.coregroup.multicastgroupipend", None), "multiCastGroupIPEnd","CoreGroup");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.coregroup.numcoordinators", None), "numCoordinators","CoreGroup");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.coregroup.description", None), "description","CoreGroup");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.coregroup.transporttype", None), "transportType","CoreGroup");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.coregroup.multicastport", None), "multiCastPort","CoreGroup");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.coregroup.channelchainname", None), "channelChainName","CoreGroup");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.coregroup.coregroupuid", None), "coreGroupUID","CoreGroup");
  if len(atts) != 0:
    print "Modifying CoreGroup with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  #remove liveness and recreate it
  liveness = Util.getOptionalAttribute(objid, 'liveness', 'CoreGroup');
  if liveness is not None and len(liveness) > 0:
    Util.remove(liveness);

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

  Util.modify(objid, [['preferredCoordinatorServers','']]);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereCoreGroupServer":
        CoreGroupServer.create(objid, curjsonobject);
      elif currole == "WebSphereCoreGroupServerRef":
        CoreGroupServerRef.create(objid, curjsonobject);
      elif currole == "WebSphereLiveness":
        Liveness.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('CoreGroup');
