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

__name_att__ = "websphere.nodegroup.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.nodegroup.shortname", objid, "shortName","NodeGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.nodegroup.name", objid, "name","NodeGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.nodegroup.description", objid, "description","NodeGroup");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"NodeGroup");
  secfolderretdict = Util.createTypeFolder(respath, "Security", typeFolders);
  secresfolpath = secfolderretdict['path'];
  if secfolderretdict.has_key('object'):
    Util.addFromExport(extraObjects, secfolderretdict['object']);
  Util.addAllFromExport(extraObjects, Security._export(objid, secresfolpath, "Security"));

  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('NodeGroup');
  return result;



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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "shortName", roleProperties.optString("websphere.nodegroup.shortname", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.nodegroup.name", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.nodegroup.description", None));
  print "Creating NodeGroup with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("NodeGroup", parentid, properties);
  
  groupmembers = Util.parseConfigIdListAttribute(objid, 'members',"NodeGroup");
  for groupmember in groupmembers:
    if len(groupmember) > 0:
      Util.remove(groupmember);

  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    for curjsonobject in children:
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereNodeGroupMember":
        NodeGroupMember.create(objid, curjsonobject);      
      elif currole == "WebSphereSecurity":
        Security.update(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('NodeGroup');
  
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

    Util.modify(objid, atts);
  else:   
    print "NodeGroup configuration up to date.";
  
  groupmembers = Util.parseConfigIdListAttribute(objid, 'members',"NodeGroup");
  for groupmember in groupmembers:
    if len(groupmember) > 0:
      Util.remove(groupmember);

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

  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    for curjsonobject in children:
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereNodeGroupMember":
        NodeGroupMember.create(objid, curjsonobject);      
      elif currole == "WebSphereSecurity":
        Security.update(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);

  Util.popPathElement('NodeGroup');
