###
# Licensed Materials - Property of IBM* and/or HCL**
# (c) Copyright IBM Corporation 2014, 2015, 2017. All Rights Reserved.
# (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
#
# U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
# GSA ADP Schedule Contract with IBM Corp.
#
# * Trademark of International Business Machines
# ** Trademark of HCL Technologies Limited

from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from AuditPolicy import AuditPolicy
from AuditSpecification import AuditSpecification
from KeyStore import KeyStore
from Certificate import Certificate
from CACertificate import CACertificate

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  auditPolicy = Util.getOptionalAttribute(objid, 'auditPolicy',"Audit");
  if auditPolicy is not None and len(auditPolicy) > 0:
    returndict = Util.createTypeFolder(respath, "AuditPolicy", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, AuditPolicy._export(auditPolicy, currespath, "AuditPolicy"));    
  
  i = 0;
  auditSpecs = Util.parseConfigIdListAttribute(objid, 'auditSpecifications', 'Audit');
  for auditSpec in auditSpecs:
    if len(auditSpec) > 0:
      returndict = Util.createTypeFolder(respath, "AuditSpecification", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      specName = Util.getOptionalAttribute(auditSpec, "name", "AuditSpecification");
      if specName is not None and len(specName) > 0:
        resourceName = specName;
      else:
        resourceName = "AuditSpecification%s" % i;
      Util.addAllFromExport(extraObjects, AuditSpecification._export(auditSpec, currespath, resourceName));
      i = i + 1;

  i = 0;
  keyStores = Util.parseConfigIdListAttribute(objid, 'keyStores', "Audit");
  for keyStore in keyStores:
    if len(keyStore) > 0:
      returndict = Util.createTypeFolder(respath, "KeyStore", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
  # KeyStore names are not unique
      Util.addAllFromExport(extraObjects, KeyStore._export(keyStore, currespath, "KeyStore%s" % i));
      i = i + 1;      

  i = 0;    
  cai = 0;
  certificates = Util.parseConfigIdListAttribute(objid, 'certificates',"Audit");
  for certificate in certificates:
    if len(certificate) > 0:
      returndict = Util.createTypeFolder(respath, "Certificate", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      if certificate.find("#Certificate_") != -1:
        Util.addAllFromExport(extraObjects, Certificate._export(certificate, currespath, "Certificate%s" % i));
        i = i + 1;
      elif certificate.find("#CACertificate_") != -1:
        Util.addAllFromExport(extraObjects, CACertificate._export(certificate, currespath, "CACertificate%s" % i));      
        cai = cai + 1;            

      
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('Audit');
  return result;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  print "Creating Audit with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("Audit", parentid, properties);
  
  auditPolicy = Util.getOptionalAttribute(objid, 'auditPolicy',"Audit");
  if auditPolicy is not None and len(auditPolicy) > 0:
    Util.remove(auditPolicy);

  # Must create AuditSpecifications 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 == "WebSphereAuditSpecification":
        AuditSpecification.create(objid, curjsonobject);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");  
      if currole == "WebSphereAuditPolicy":
        AuditPolicy.create(objid, curjsonobject);
      elif currole == "WebSphereKeyStore":
        KeyStore.create(objid, curjsonobject);        
      elif currole == "WebSphereCertificate":
        Certificate.create(objid, curjsonobject);       
      elif currole == "WebSphereCACertificate":
        CACertificate.create(objid, curjsonobject);                        
  Util.popPathElement('Audit');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  if len(atts) != 0:
    print "Modifying Audit with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

    Util.modify(objid, atts);
  else:   
    print "Audit configuration up to date.";
    
  auditPolicy = Util.getOptionalAttribute(objid, 'auditPolicy',"Audit");
  if auditPolicy is not None and len(auditPolicy) > 0:
    Util.remove(auditPolicy);

  auditSpecs = Util.parseConfigIdListAttribute(objid, 'auditSpecifications', 'Audit');
  for auditSpec in auditSpecs:
    if len(auditSpec) > 0:
      Util.remove(auditSpec);

  # Cannot delete KeyStores.  We can only update them because we are corrupting the password
  # field when we try to create them.

  # Must create KeyStores 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 == "WebSphereKeyStore":
        keyStoreToUpdate = KeyStore.find(objid, curjsonobject);
        if keyStoreToUpdate is not None or len(keyStoreToUpdate) > 0:
          KeyStore.update(keyStoreToUpdate, curjsonobject);
        else:
          KeyStore.create(objid, curjsonobject); 

  # Must create AuditSpecifications 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 == "WebSphereAuditSpecification":
        AuditSpecification.create(objid, curjsonobject);
  
  certificates = Util.parseConfigIdListAttribute(objid, 'certificates',"Audit");
  for certificate in certificates:
    if len(certificate) > 0:
      if certificate.find("#CACertificate_") != -1:
        Util.remove(certificate);   
      

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");  
      if currole == "WebSphereAuditPolicy":
        AuditPolicy.create(objid, curjsonobject);
      elif currole == "WebSphereCertificate":
        certificateToUpdate = Certificate.find(objid, curjsonobject);
        if certificateToUpdate is not None or len(certificateToUpdate) > 0:
          Certificate.update(certificateToUpdate, curjsonobject);
      elif currole == "WebSphereCACertificate":
        CACertificate.create(objid, curjsonobject);                             
        

  Util.popPathElement('Audit');
