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

__name_att__ = None;

def _export(nodeobjid, noderespath):
  #Check to make sure that it is okay for node to belong to a nodegroup.
  nodename = Util.getRequiredAttribute(nodeobjid, 'name', 'Node');
  if Util.isJ2EENode(nodename) == 0:
    return;

  Util.pushPathElement('NodeGroupMapping')
  extraObjects = [];
  typeFolders = {};

  nmFoldName = Util.getTypeFoldername("NodeGroupMapping");
  if noderespath == "/":
    noderespath = "";
  folpath = "%(parentrespath)s/%(name)s" % { 'parentrespath':noderespath, 'name':nmFoldName }
  if not folpath.startswith("/"):
    folpath = "/" + folpath;


  folderObject = JSONObject();
  folderObject.put("name", nmFoldName);
  folderObject.put("path", folpath);
  folderObject.put("inheritTeam", "true");
  folderObject.put("description", "Discovered WebSphereNodeGroupMapping");

  respath = "%(cur)s/%(res)s" % { 'cur':folpath, 'res':nmFoldName};

  exportedObject = JSONObject();
  exportedObject.put("name", nmFoldName);
  exportedObject.put("path", respath);
  exportedObject.put("teamMappings", JSONArray());
  exportedObject.put("inheritTeam", "true");
  exportedObject.put("description", "Discovered WebSphereNodeGroupMapping");
  exportedObject.put("roleName", "WebSphereNodeGroupMapping");
  roleProperties = JSONObject();
  exportedObject.put("roleProperties", roleProperties);

  ngAndNgm = getNodeGroupAndNodeGroupMemberForNode(nodeobjid);
  if ngAndNgm is None:
    raise Exception("Could not find node group membership for node %s" % nodeobjid);
  ng = ngAndNgm['nodeGroup'];
  ngm = ngAndNgm['nodeGroupMember'];
  ngName = Util.getRequiredAttribute(ng, 'name', 'NodeGroup');
  roleProperties.put("websphere.nodegroupmapping.nodegroupname", ngName);

  result = { 'object': exportedObject, 'respath':respath }

  extraObjects = Property.exportProperties(ngm, respath, extraObjects, typeFolders, 'properties',"NodeGroupMember");
  extraObjects.append(folderObject);

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  ngName = roleProperties.getString("websphere.nodegroupmapping.nodegroupname");
  nodeName = Util.getRequiredAttribute(parentid, 'name', 'Node');
  properties.append(['nodeName', nodeName]);
  correctng = Util.getid("/NodeGroup:%s/" % ngName);

  #we will alwyas delete the node membership to make life a litte easier
  ngAndNgm = getNodeGroupAndNodeGroupMemberForNode(parentid);
  if ngAndNgm is None:
    #didn't find an already existing nodegroupmember... odd
    #perrrrfeecctt
    pass;
  else:
    ng = ngAndNgm['nodeGroupMember'];
    Util.remove(ng, 1);

  objid = Util.create('NodeGroupMember', correctng, properties);

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

  return objid;

def getNodeGroupAndNodeGroupMemberForNode(nodeobjid):
  nodename = Util.getRequiredAttribute(nodeobjid, 'name', 'Node');
  nodegroups = Util.getAssociatedObjects(None, 'NodeGroup', 1);
  if nodegroups is not None and len(nodegroups) > 0:
    for ng in nodegroups:
      ngname = Util.getRequiredAttribute(ng, 'name', 'NodeGroup');
      nodesingroup = Util.parseConfigIdListAttribute(ng, 'members', 'NodeGroup');
      for member in nodesingroup:
        membernodename = Util.getRequiredAttribute(member, 'nodeName', 'NodeGroupMember');
        if membernodename == nodename:
          return { 'nodeGroup': ng, 'nodeGroupMember': member };
  return None;
