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

__name_att__ = None;


def _export(parentrespath, name, resname):
  Util.pushPathElement('JMXConnectorRef')


  if parentrespath == "/":
    parentrespath = "";
  respath = "%(parentrespath)s/%(name)s" % { 'parentrespath':parentrespath, 'name':resname }
  if not respath.startswith("/"):
    respath = "/" + respath;

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

  roleProperties = JSONObject();

  roleProperties.put("websphere.jmxconnectorref.name", name);
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('JMXConnectorRef');
  return result;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has('websphere.jmxconnectorref.name'):
    raise Exception("JMXConnectorRef resource has property named websphere.jmxconnectorref.name!");

  conname = roleProperties.getString('websphere.jmxconnectorref.name')

  if not connectorName2IdDict.has_key(conname):
    raise Exception("No JMXConnector with name %s defined for Admin Service!" % conname);

  conid = connectorName2IdDict[conname];

  properties = [];
  properties.append([parentAtt, conid]);
  Log.debug(properties);
  Log.debug(parentid);
  print "Creating JMXConnectorRef to %(id)s for attribute %(att)s" % { 'id':conid, 'att':parentAtt };
  objid = Util.modify(parentid, properties);
  Log.debug("Finished Creating JMXConnectorRef to %(id)s for attribute %(att)s" % { 'id':conid, 'att':parentAtt });
  Util.popPathElement('JMXConnectorRef');
