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

__name_att__ = None;


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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.coregroupserver.servername", objid, "serverName","CoreGroupServer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.coregroupserver.nodename", objid, "nodeName","CoreGroupServer");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('CoreGroupServerRef');
  return result;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  nodename = roleProperties.getString('websphere.coregroupserver.nodename')
  servername = roleProperties.getString('websphere.coregroupserver.servername')

  if coreGroupServers is None:
    coreGroupServers = Util.parseConfigIdListAttribute(parentid, 'coreGroupServers',"CoreGroup");
  finObjId = None;
  if coreGroupServers is not None and len(coreGroupServers) > 0:
    for server in coreGroupServers:
      if Util.getRequiredAttribute(server, 'nodeName', 'CoreGroupServer') == nodename and Util.getRequiredAttribute(server, 'serverName', 'CoreGroupServer') == servername:
        finObjId = server;
        break;

  if finObjId is None:
    raise Exception("Cannot find CoreGroupServer for CoreGroupServerRef %(node)s:%(server)s" % { 'node':nodename, 'server':servername });

  properties = [];
  properties.append([parentAtt, finObjId]);
  print "Creating CoreGroupServerRef to %s" % finObjId;
  objid = Util.modify(parentid, properties);
  Util.popPathElement('CoreGroupServerRef');
