from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from Property import Property
from AuditEventFactory import AuditEventFactory
from AuditServiceProvider import AuditServiceProvider
from CertificateRef import CertificateRef
from ManagementScopeRef import ManagementScopeRef

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.auditpolicy.batching", objid, "batching","AuditPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.auditpolicy.securityxmlsignerkeystorename", objid, "securityXmlSignerKeyStoreName","AuditPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.auditpolicy.auditenabled", objid, "auditEnabled","AuditPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.auditpolicy.sign", objid, "sign","AuditPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.auditpolicy.auditorpwd", objid, "auditorPwd","AuditPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.auditpolicy.verbose", objid, "verbose","AuditPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.auditpolicy.securityxmlsignerscopename", objid, "securityXmlSignerScopeName","AuditPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.auditpolicy.securityxmlsignercertalias", objid, "securityXmlSignerCertAlias","AuditPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.auditpolicy.auditorid", objid, "auditorId","AuditPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.auditpolicy.encrypt", objid, "encrypt","AuditPolicy");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.auditpolicy.auditpolicy", objid, "auditPolicy","AuditPolicy");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  i = 0;
  auditEventFactories = Util.parseConfigIdListAttribute(objid, 'auditEventFactories', "AuditPolicy");
  for auditEventFactory in auditEventFactories:
    if len(auditEventFactory) > 0:
      returndict = Util.createTypeFolder(respath, "AuditEventFactory", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, AuditEventFactory._export(auditEventFactory, currespath, Util.getRequiredAttribute(auditEventFactory, "name", "AuditEventFactory")));
      i = i + 1;

  i = 0;
  auditServiceProviders = Util.parseConfigIdListAttribute(objid, 'auditServiceProviders', "AuditPolicy");
  for auditServiceProvider in auditServiceProviders:
    if len(auditServiceProvider) > 0:
      returndict = Util.createTypeFolder(respath, "AuditServiceProvider", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, AuditServiceProvider._export(auditServiceProvider, currespath, Util.getRequiredAttribute(auditServiceProvider, "name", "AuditServiceProvider")));
      i = i + 1;

  certificate = Util.getOptionalAttribute(objid, 'encrytionCert', 'AuditPolicy');
  if certificate is not None and len(certificate) > 0:
    returndict = Util.createTypeFolder(respath, "CertificateRef", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, CertificateRef._export(certificate, currespath, Util.getRequiredAttribute(certificate, 'alias', 'Certificate')));

  managementScope = Util.getOptionalAttribute(objid, 'managementScope', 'AuditPolicy');
  if managementScope is not None and len(managementScope) > 0:
    returndict = Util.createTypeFolder(respath, "ManagementScopeRef", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, ManagementScopeRef._export(managementScope, currespath, "ManagementScope"));

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"AuditPolicy");
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('AuditPolicy');
  return result;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "batching", roleProperties.optString("websphere.auditpolicy.batching", None));
  Util.addIfNotNone(properties, "securityXmlSignerKeyStoreName", roleProperties.optString("websphere.auditpolicy.securityxmlsignerkeystorename", None));
  Util.addIfNotNone(properties, "auditEnabled", roleProperties.optString("websphere.auditpolicy.auditenabled", None));
  Util.addIfNotNone(properties, "sign", roleProperties.optString("websphere.auditpolicy.sign", None));
  Util.addIfNotNone(properties, "auditorPwd", roleProperties.optString("websphere.auditpolicy.auditorpwd", None));
  Util.addIfNotNone(properties, "verbose", roleProperties.optString("websphere.auditpolicy.verbose", None));
  Util.addIfNotNone(properties, "securityXmlSignerScopeName", roleProperties.optString("websphere.auditpolicy.securityxmlsignerscopename", None));
  Util.addIfNotNone(properties, "securityXmlSignerCertAlias", roleProperties.optString("websphere.auditpolicy.securityxmlsignercertalias", None));
  Util.addIfNotNone(properties, "auditorId", roleProperties.optString("websphere.auditpolicy.auditorid", None));
  Util.addIfNotNone(properties, "encrypt", roleProperties.optString("websphere.auditpolicy.encrypt", None));
  Util.addIfNotNone(properties, "auditPolicy", roleProperties.optString("websphere.auditpolicy.auditpolicy", None));
  print "Creating AuditPolicy with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("AuditPolicy", parentid, properties);

  # Must create AuditServiceProviders first so that references can be created later.
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereAuditServiceProvider":
        AuditServiceProvider.create(objid, curjsonobject);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if (propertyObject == 1):
        continue;
      if currole == "WebSphereAuditEventFactory":
        AuditEventFactory.create(objid, curjsonobject);
      elif currole == "WebSphereCertificateRef":
        CertificateRef.create(objid, curjsonobject, "encryptionCert");
      elif currole == "WebSphereManagementScopeRef":
        ManagementScopeRef.create(objid, curjsonobject, "managementScope");

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.auditpolicy.batching", None), "batching","AuditPolicy");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.auditpolicy.securityxmlsignerkeystorename", None), "securityXmlSignerKeyStoreName","AuditPolicy");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.auditpolicy.auditenabled", None), "auditEnabled","AuditPolicy");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.auditpolicy.sign", None), "sign","AuditPolicy");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.auditpolicy.auditorpwd", None), "auditorPwd","AuditPolicy");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.auditpolicy.verbose", None), "verbose","AuditPolicy");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.auditpolicy.securityxmlsignerscopename", None), "securityXmlSignerScopeName","AuditPolicy");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.auditpolicy.securityxmlsignercertalias", None), "securityXmlSignerCertAlias","AuditPolicy");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.auditpolicy.auditorid", None), "auditorId","AuditPolicy");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.auditpolicy.encrypt", None), "encrypt","AuditPolicy");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.auditpolicy.auditpolicy", None), "auditPolicy","AuditPolicy");
  if len(atts) != 0:
    print "Modifying AuditPolicy with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  auditEventFactories = Util.parseConfigIdListAttribute(objid, 'auditEventFactories', "AuditPolicy");
  for auditEventFactory in auditEventFactories:
    Util.remove(auditEventFactory);

  auditServiceProviders = Util.parseConfigIdListAttribute(objid, 'auditServiceProviders', "AuditPolicy");
  for auditServiceProvider in auditServiceProviders:
    Util.remove(auditServiceProvider);

  Property.removeProperties(objid, 'properties',"AuditPolicy");

  Util.unsetAttribute(objid, "encryptionCert", "AuditPolicy");

  Util.unsetAttribute(objid, "managementScope", "AuditPolicy");

  # Must create AuditServiceProviders first so that references can be created later.
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereAuditServiceProvider":
        AuditServiceProvider.create(objid, curjsonobject);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if (propertyObject == 1):
        continue;
      if currole == "WebSphereAuditEventFactory":
        AuditEventFactory.create(objid, curjsonobject);
      elif currole == "WebSphereCertificateRef":
        CertificateRef.create(objid, curjsonobject, "encryptionCert");
      elif currole == "WebSphereManagementScopeRef":
        ManagementScopeRef.create(objid, curjsonobject, "managementScope");

  Util.popPathElement('AuditPolicy');
