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

__name_att__ = "websphere.clustermember.membername";

def export(objid, parentcontainmentpath, parentrespath):

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

  containmentpath = "%(parentconpath)sClusterMember:%(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, name = ""):
  Util.pushPathElement('ClusterMember')

  memberName = Util.getRequiredAttribute(objid, "memberName", 'ClusterMember');
  nodeName = Util.getRequiredAttribute(objid, "nodeName", 'ClusterMember');
  name = nodeName + "-" + memberName;

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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.clustermember.membername", objid, "memberName","ClusterMember");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.clustermember.weight", objid, "weight","ClusterMember");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.clustermember.nodename", objid, "nodeName","ClusterMember");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('ClusterMember');
  return result;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.clustermember.membername"):
    raise Exception("Resource role properties does not contain websphere.clustermember.membername!");

  properties = [];
  Util.addIfNotNone(properties, "memberName", roleProperties.optString("websphere.clustermember.membername", None));
  Util.addIfNotNone(properties, "weight", roleProperties.optString("websphere.clustermember.weight", None));
  Util.addIfNotNone(properties, "nodeName", roleProperties.optString("websphere.clustermember.nodename", None));
  membername = roleProperties.optString("websphere.clustermember.membername");
  nodename = roleProperties.optString("websphere.clustermember.nodename");
  print "Creating ClusterMember with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  server = Util.getid("/Node:%(node)s/Server:%(server)s/" % {'node':nodename, 'server':membername});
  if server is None or len(server) < 1:
    message = "Warning: Trying to create a cluster member, but server %(server)s not found on node %(node)s" % {'server':membername, 'node':nodename};
    Log.logMsg(message, Log.LogLevelWarn);
  else:
    objid = Util.create("ClusterMember", parentid, properties);

  Util.popPathElement('ClusterMember');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.clustermember.membername"):
    raise Exception("Resource role properties does not contain websphere.clustermember.membername!");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.clustermember.membername", None), "memberName","ClusterMember");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.clustermember.weight", None), "weight","ClusterMember");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.clustermember.nodename", None), "nodeName","ClusterMember");
  if len(atts) != 0:
    print "Modifying ClusterMember with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Util.popPathElement('ClusterMember');
