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

__name_att__ = None;


def _export(objid, parentrespath, resname):
  Util.pushPathElement('WSNotificationRef')

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

  roleProperties = JSONObject();
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wsnotificationref.name", objid, "name", "WSNotification");

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

def create(parentid, jsonobject, parentAtt):
  Util.pushPathElement('WSNotificationRef')

  if not jsonobject.has("roleProperties"):
    raise Exception("WSNotificationRef resource has no role properties!");

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

  name = roleProperties.getString('websphere.wsnotificationref.name');

  wsnotificationId = None;
  wsnotifications = Util.getid("/WSNotification:/").splitlines();
  if len(wsnotifications) > 0:
    for wsnotification in wsnotifications:
      if len(wsnotification) > 0:
        wsnotificationname = Util.getRequiredAttribute(wsnotification, "name", "WSNotification");
        if (name == wsnotificationname):
          wsnotificationId = wsnotification;
          break;

  if wsnotificationId is None or len(wsnotificationId) < 1:
    raise Exception("Could not find wsnotification named %(name)s" % { 'name': name } );

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