#- Licensed Materials - Property of IBM Corp.
#- IBM UrbanCode Deploy
#- (c) Copyright IBM Corporation 2014, 2015. All Rights Reserved.
#-
#- U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
#- GSA ADP Schedule Contract with IBM Corp.

from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from Property import Property
from KeyStoreRef import KeyStoreRef
from CertificateRef import CertificateRef
from TrustAssociation import TrustAssociation
from SingleSignon import SingleSignon
from DigestAuthentication import DigestAuthentication

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.rsatoken.simpleauthconfig", objid, "simpleAuthConfig","RSAToken");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.rsatoken.noncecachetimeout", objid, "nonceCacheTimeout","RSAToken");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.rsatoken.authcontextimplclass", objid, "authContextImplClass","RSAToken");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.rsatoken.tokenexpiration", objid, "tokenExpiration","RSAToken");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.rsatoken.authconfig", objid, "authConfig","RSAToken");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.rsatoken.iscredentialforwardable", objid, "isCredentialForwardable","RSAToken");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.rsatoken.oid", objid, "OID","RSAToken");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.rsatoken.authvalidationconfig", objid, "authValidationConfig","RSAToken");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"RSAToken");

  keyStore = Util.getOptionalAttribute(objid, 'adminCertificateTrustStore', 'RSAToken');
  if keyStore is not None and len(keyStore) > 0:
    returndict = Util.createTypeFolder(respath, "KeyStoreRef", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, KeyStoreRef._export(keyStore, currespath, "AdminCertificateTrustStore"));

  certificate = Util.getOptionalAttribute(objid, 'adminCertificate', 'RSAToken');
  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')));

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

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

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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "simpleAuthConfig", roleProperties.optString("websphere.rsatoken.simpleauthconfig", None));
  Util.addIfNotNone(properties, "nonceCacheTimeout", roleProperties.optString("websphere.rsatoken.noncecachetimeout", None));
  Util.addIfNotNone(properties, "authContextImplClass", roleProperties.optString("websphere.rsatoken.authcontextimplclass", None));
  Util.addIfNotNone(properties, "tokenExpiration", roleProperties.optString("websphere.rsatoken.tokenexpiration", None));
  Util.addIfNotNone(properties, "authConfig", roleProperties.optString("websphere.rsatoken.authconfig", None));
  Util.addIfNotNone(properties, "isCredentialForwardable", roleProperties.optString("websphere.rsatoken.iscredentialforwardable", None));
  Util.addIfNotNone(properties, "OID", roleProperties.optString("websphere.rsatoken.oid", None));
  Util.addIfNotNone(properties, "authValidationConfig", roleProperties.optString("websphere.rsatoken.authvalidationconfig", None));
  print "Creating RSAToken with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("RSAToken", parentid, properties);
  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 == "WebSphereKeyStoreRef":
        KeyStoreRef.create(objid, curjsonobject, "adminCertificateTrustStore");
      elif currole == "WebSphereCertificateRef":
        CertificateRef.create(objid, curjsonobject, "adminCertificate");
      elif currole == "WebSphereTrustAssociation":
        TrustAssociation.create(objid, curjsonobject);
      elif currole == "WebSphereSingleSignon":
        SingleSignon.create(objid, curjsonobject);
      elif currole == "WebSphereDigestAuthentication":
        DigestAuthentication.create(objid, curjsonobject);
  Util.popPathElement('RSAToken');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.rsatoken.simpleauthconfig", None), "simpleAuthConfig","RSAToken");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.rsatoken.noncecachetimeout", None), "nonceCacheTimeout","RSAToken");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.rsatoken.authcontextimplclass", None), "authContextImplClass","RSAToken");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.rsatoken.tokenexpiration", None), "tokenExpiration","RSAToken");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.rsatoken.authconfig", None), "authConfig","RSAToken");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.rsatoken.iscredentialforwardable", None), "isCredentialForwardable","RSAToken");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.rsatoken.oid", None), "OID","RSAToken");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.rsatoken.authvalidationconfig", None), "authValidationConfig","RSAToken");
  if len(atts) != 0:
    print "Modifying RSAToken with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Property.removeProperties(objid, 'properties',"RSAToken");
  digest = Util.getOptionalAttribute(objid, 'digestAuthentication', 'RSAToken');
  if digest is not None and len(digest) > 0:
    Util.remove(digest);
  trust = Util.getOptionalAttribute(objid, 'trustAssociation', 'RSAToken');
  if trust is not None and len(trust) > 0:
    Util.remove(trust);
  sso = Util.getOptionalAttribute(objid, 'singleSignon', 'RSAToken');
  if sso is not None and len(sso) > 0:
    Util.remove(sso);

  Util.unsetAttribute(objid, "adminCertificateTrustStore", "RSAToken");
  Util.unsetAttribute(objid, "adminCertificate", "RSAToken");

  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 == "WebSphereKeyStoreRef":
        KeyStoreRef.create(objid, curjsonobject, "adminCertificateTrustStore");
      elif currole == "WebSphereCertificateRef":
        CertificateRef.create(objid, curjsonobject, "adminCertificate");
      elif currole == "WebSphereTrustAssociation":
        TrustAssociation.create(objid, curjsonobject);
      elif currole == "WebSphereSingleSignon":
        SingleSignon.create(objid, curjsonobject);
      elif currole == "WebSphereDigestAuthentication":
        DigestAuthentication.create(objid, curjsonobject);
  Util.popPathElement('RSAToken');
