from org.codehaus.jettison.json import JSONObject, JSONArray
from utilities import Util
from WASConfLog import Log
from Property import Property
from KeyStoreRef import KeyStoreRef
from KeyManagerRef import KeyManagerRef
from TrustManagerRef import TrustManagerRef
from CryptoHardwareToken import CryptoHardwareToken

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securesocketlayer.keyfilename", objid, "keyFileName","SecureSocketLayer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securesocketlayer.enablecryptohardwaresupport", objid, "enableCryptoHardwareSupport","SecureSocketLayer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securesocketlayer.serverkeyalias", objid, "serverKeyAlias","SecureSocketLayer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securesocketlayer.sslprotocol", objid, "sslProtocol","SecureSocketLayer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securesocketlayer.clientauthentication", objid, "clientAuthentication","SecureSocketLayer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securesocketlayer.securitylevel", objid, "securityLevel","SecureSocketLayer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securesocketlayer.keyfileformat", objid, "keyFileFormat","SecureSocketLayer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securesocketlayer.enabledciphers", objid, "enabledCiphers","SecureSocketLayer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securesocketlayer.trustfileformat", objid, "trustFileFormat","SecureSocketLayer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securesocketlayer.clientauthenticationsupported", objid, "clientAuthenticationSupported","SecureSocketLayer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securesocketlayer.keyfilepassword", objid, "keyFilePassword","SecureSocketLayer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securesocketlayer.jsseprovider", objid, "jsseProvider","SecureSocketLayer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securesocketlayer.clientkeyalias", objid, "clientKeyAlias","SecureSocketLayer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securesocketlayer.trustfilename", objid, "trustFileName","SecureSocketLayer");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securesocketlayer.trustfilepassword", objid, "trustFilePassword","SecureSocketLayer");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

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

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

  keyStore = Util.getOptionalAttribute(objid, 'keyStore', 'SecureSocketLayer');
  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, "KeyStore"));

  i = 0;
  trustManagers = Util.parseConfigIdListAttribute(objid, 'trustManager',"SecureSocketLayer");
  for trustManager in trustManagers:
    if len(trustManager) > 0:
      returndict = Util.createTypeFolder(respath, "TrustManagerRef", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, TrustManagerRef._export(trustManager, currespath,  "TrustManager%s" % i));
      i = i + 1;

  trustStore = Util.getOptionalAttribute(objid, 'trustStore', 'SecureSocketLayer');
  if trustStore is not None and len(trustStore) > 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(trustStore, currespath, "TrustStore"));

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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "keyFileName", roleProperties.optString("websphere.securesocketlayer.keyfilename", None));
  Util.addIfNotNone(properties, "enableCryptoHardwareSupport", roleProperties.optString("websphere.securesocketlayer.enablecryptohardwaresupport", None));
  Util.addIfNotNone(properties, "serverKeyAlias", roleProperties.optString("websphere.securesocketlayer.serverkeyalias", None));
  Util.addIfNotNone(properties, "sslProtocol", roleProperties.optString("websphere.securesocketlayer.sslprotocol", None));
  Util.addIfNotNone(properties, "clientAuthentication", roleProperties.optString("websphere.securesocketlayer.clientauthentication", None));
  Util.addIfNotNone(properties, "securityLevel", roleProperties.optString("websphere.securesocketlayer.securitylevel", None));
  Util.addIfNotNone(properties, "keyFileFormat", roleProperties.optString("websphere.securesocketlayer.keyfileformat", None));
  Util.addIfNotNone(properties, "enabledCiphers", roleProperties.optString("websphere.securesocketlayer.enabledciphers", None));
  Util.addIfNotNone(properties, "trustFileFormat", roleProperties.optString("websphere.securesocketlayer.trustfileformat", None));
  Util.addIfNotNone(properties, "clientAuthenticationSupported", roleProperties.optString("websphere.securesocketlayer.clientauthenticationsupported", None));
  Util.addIfNotNone(properties, "keyFilePassword", roleProperties.optString("websphere.securesocketlayer.keyfilepassword", None));
  Util.addIfNotNone(properties, "jsseProvider", roleProperties.optString("websphere.securesocketlayer.jsseprovider", None));
  Util.addIfNotNone(properties, "clientKeyAlias", roleProperties.optString("websphere.securesocketlayer.clientkeyalias", None));
  Util.addIfNotNone(properties, "trustFileName", roleProperties.optString("websphere.securesocketlayer.trustfilename", None));
  Util.addIfNotNone(properties, "trustFilePassword", roleProperties.optString("websphere.securesocketlayer.trustfilepassword", None));
  print "Creating SecureSocketLayer with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("SecureSocketLayer", parentid, properties);
  if jsonobject.has('children'):
    for currjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = currjsonobject.getString('roleName');
      propertyObject = 0;
      propertyObject = Property.createObjIfRole(objid, currjsonobject, currole);
      if (propertyObject == 0):
        if currole == "WebSphereKeyStoreRef":
          currname = currjsonobject.getString('name');
          if currname == "TrustStore":
             KeyStoreRef.create(objid, currjsonobject, "trustStore");
          elif currname == "KeyStore":
             KeyStoreRef.create(objid, currjsonobject, "keyStore");
          else:
             Log.log("Invalid name %(name)s for WebSphereKeyStoreRef" % { 'name': currname });
        elif currole == "WebSphereKeyManagerRef":
          KeyManagerRef.create(objid, currjsonobject, "keyManager");
        elif currole == "WebSphereTrustManagerRef":
          TrustManagerRef.create(objid, currjsonobject, "trustManager");
        elif currole == "WebSphereCryptoHardwareToken":
          CryptoHardwareToken.create(objid, currjsonobject, "cryptoHardware");
  Util.popPathElement('SecureSocketLayer');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securesocketlayer.keyfilename", None), "keyFileName","SecureSocketLayer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securesocketlayer.enablecryptohardwaresupport", None), "enableCryptoHardwareSupport","SecureSocketLayer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securesocketlayer.serverkeyalias", None), "serverKeyAlias","SecureSocketLayer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securesocketlayer.sslprotocol", None), "sslProtocol","SecureSocketLayer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securesocketlayer.clientauthentication", None), "clientAuthentication","SecureSocketLayer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securesocketlayer.securitylevel", None), "securityLevel","SecureSocketLayer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securesocketlayer.keyfileformat", None), "keyFileFormat","SecureSocketLayer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securesocketlayer.enabledciphers", None), "enabledCiphers","SecureSocketLayer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securesocketlayer.trustfileformat", None), "trustFileFormat","SecureSocketLayer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securesocketlayer.clientauthenticationsupported", None), "clientAuthenticationSupported","SecureSocketLayer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securesocketlayer.keyfilepassword", None), "keyFilePassword","SecureSocketLayer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securesocketlayer.jsseprovider", None), "jsseProvider","SecureSocketLayer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securesocketlayer.clientkeyalias", None), "clientKeyAlias","SecureSocketLayer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securesocketlayer.trustfilename", None), "trustFileName","SecureSocketLayer");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.securesocketlayer.trustfilepassword", None), "trustFilePassword","SecureSocketLayer");
  if len(atts) != 0:
    print "Modifying SecureSocketLayer with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

  Util.unsetAttribute(objid, "keyManager", "SecureSocketLayer");
  Util.unsetAttribute(objid, "keyStore", "SecureSocketLayer");
  Util.unsetAttribute(objid, "trustManager", "SecureSocketLayer");
  Util.unsetAttribute(objid, "trustStore", "SecureSocketLayer");

  cryptoHardware = Util.getOptionalAttribute(objid, 'cryptoHardware', 'SecureSocketLayer');
  if cryptoHardware is not None and len(cryptoHardware) > 0:
    Util.remove(cryptoHardware);

  if jsonobject.has('children'):
    for currjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = currjsonobject.getString('roleName');
      propertyObject = 0;
      propertyObject = Property.createObjIfRole(objid, currjsonobject, currole);
      if (propertyObject == 0):
        if currole == "WebSphereKeyStoreRef":
          currname = currjsonobject.getString('name');
          if currname == "TrustStore":
             KeyStoreRef.create(objid, currjsonobject, "trustStore");
          elif currname == "KeyStore":
             KeyStoreRef.create(objid, currjsonobject, "keyStore");
          else:
             Log.log("Invalid name %(name)s for WebSphereKeyStoreRef" % { 'name': currname });
        elif currole == "WebSphereKeyManagerRef":
          KeyManagerRef.create(objid, currjsonobject, "keyManager");
        elif currole == "WebSphereTrustManagerRef":
          TrustManagerRef.create(objid, currjsonobject, "trustManager");
        elif currole == "WebSphereCryptoHardwareToken":
          CryptoHardwareToken.create(objid, currjsonobject, "cryptoHardware");
  Util.popPathElement('SecureSocketLayer');
