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

__name_att__ = None;


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

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

  roleProperties = JSONObject();
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.auditspecificationref.name", objid, "name","AuditSpecification");
  
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('AuditSpecificationRef');
  return result;

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

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

  name = roleProperties.getString('websphere.auditspecificationref.name')

  auditSpecificationId = None;
  auditSpecifications = Util.getid("/AuditSpecification:/").splitlines();
  if len(auditSpecifications) > 0:
    for auditSpecification in auditSpecifications:
      if len(auditSpecification) > 0:
        auditSpecificationName = Util.getRequiredAttribute(auditSpecification, "name", "AuditSpecification" );
        
        if (name == auditSpecificationName):
          auditSpecificationId = auditSpecification;
          break;
  
  if auditSpecificationId is None or len(auditSpecificationId) < 1:
    raise Exception("Could not find audit specification named %(name)s" % { 'name':name } );

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