from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from KeyStoreRef import KeyStoreRef
from ManagementScopeRef import ManagementScopeRef
from Property import Property
from KeyReference import KeyReference
from WASConfLog import Log

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keyset.name", objid, "name","KeySet");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keyset.keygenerationclass", objid, "keyGenerationClass","KeySet");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keyset.maxkeyreferences", objid, "maxKeyReferences","KeySet");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keyset.deleteoldkeys", objid, "deleteOldKeys","KeySet");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keyset.iskeypair", objid, "isKeyPair","KeySet");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keyset.password", objid, "password","KeySet");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keyset.aliasprefix", objid, "aliasPrefix","KeySet");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'additionalKeySetAttrs',"KeySet","AdditionalKeySetAttrs");

  managementScope = Util.getOptionalAttribute(objid, 'managementScope', 'KeySet');
  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"));

  keyStore = Util.getOptionalAttribute(objid, 'keyStore', 'KeySet');
  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;
  keyReferences = Util.parseConfigIdListAttribute(objid, 'keyReference', "KeySet");
  for keyReference in keyReferences:
    if len(keyReference) > 0:
      returndict = Util.createTypeFolder(respath, "KeyReference", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, KeyReference._export(keyReference, currespath, "KeyReference%s" % i));
      i = i + 1;

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.keyset.name", None));
  Util.addIfNotNone(properties, "keyGenerationClass", roleProperties.optString("websphere.keyset.keygenerationclass", None));
  Util.addIfNotNone(properties, "maxKeyReferences", roleProperties.optString("websphere.keyset.maxkeyreferences", None));
  Util.addIfNotNone(properties, "deleteOldKeys", roleProperties.optString("websphere.keyset.deleteoldkeys", None));
  Util.addIfNotNone(properties, "isKeyPair", roleProperties.optString("websphere.keyset.iskeypair", None));
  Util.addIfNotNone(properties, "password", roleProperties.optString("websphere.keyset.password", None));
  Util.addIfNotNone(properties, "aliasPrefix", roleProperties.optString("websphere.keyset.aliasprefix", None));
  print "Creating KeySet with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("KeySet", parentid, properties);

  if jsonobject.has('children'):
    for currjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = currjsonobject.getString('roleName');
      attName = None;
      currpath = currjsonobject.getString('path');
      lastSlashIndex = currpath.rindex('/');
      nextToLastSlashIndex = currpath.rindex('/', 0, lastSlashIndex - 1);
      foldername = currpath[nextToLastSlashIndex+1:lastSlashIndex];
      if (foldername.find(Util.getTypeFoldername('AdditionalKeySetAttrs')) > -1):
        attName = 'additionalKeySetAttrs';
      propertObject = 0;
      propertyObject = Property.createObjIfRole(objid, currjsonobject, currole, attName);
      if (propertyObject == 0):
        if currole == "WebSphereManagementScopeRef":
          ManagementScopeRef.create(objid, currjsonobject, "managementScope");
        elif currole == "WebSphereKeyStoreRef":
          KeyStoreRef.create(objid, currjsonobject, "keyStore");
        elif currole == "WebSphereKeyReference":
          KeyReference.create(objid, currjsonobject);
  Util.popPathElement('KeySet');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keyset.name", None), "name","KeySet");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keyset.keygenerationclass", None), "keyGenerationClass","KeySet");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keyset.maxkeyreferences", None), "maxKeyReferences","KeySet");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keyset.deleteoldkeys", None), "deleteOldKeys","KeySet");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keyset.iskeypair", None), "isKeyPair","KeySet");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keyset.password", None), "password","KeySet");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keyset.aliasprefix", None), "aliasPrefix","KeySet");
  if len(atts) != 0:
    print "Modifying KeySet with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Property.removeProperties(objid, 'additionalKeySetAttrs',"KeySet");

  Util.unsetAttribute(objid, "managementScope", "KeySet");
  Util.unsetAttribute(objid, "keyStore", "KeySet");

  keyReferences = Util.parseConfigIdListAttribute(objid, 'keyReference', "KeySet");
  for keyReference in keyReferences:
    Util.remove(keyReference);
    
  if jsonobject.has('children'):
    for currjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = currjsonobject.getString('roleName');
      attName = None;
      currpath = currjsonobject.getString('path');
      lastSlashIndex = currpath.rindex('/');
      nextToLastSlashIndex = currpath.rindex('/', 0, lastSlashIndex - 1);
      foldername = currpath[nextToLastSlashIndex+1:lastSlashIndex];
      if (foldername.find(Util.getTypeFoldername('AdditionalKeySetAttrs')) > -1):
        attName = 'additionalKeySetAttrs';
      propertObject = 0;
      propertyObject = Property.createObjIfRole(objid, currjsonobject, currole, attName);
      if (propertyObject == 0):
        if currole == "WebSphereManagementScopeRef":
          ManagementScopeRef.create(objid, currjsonobject, "managementScope");
        elif currole == "WebSphereKeyStoreRef":
          KeyStoreRef.create(objid, currjsonobject, "keyStore");
        elif currole == "WebSphereKeyReference":
          KeyReference.create(objid, currjsonobject);
  Util.popPathElement('KeySet');

def find(parentid, jsonobject):

  if not jsonobject.has("roleProperties"):
    raise Exception("KeySet resource has no role properties!");

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

  keySetName = roleProperties.getString('websphere.keyset.name');
  keySetAliasPrefix = roleProperties.getString('websphere.keyset.aliasprefix');

  keySetId = None;
  keySets = Util.getid("/KeySet:/").splitlines();
  if len(keySets) > 0:
    for keySet in keySets:
      if len(keySet) > 0:
        name = Util.getRequiredAttribute(keySet, "name", "KeySet" );
        aliasPrefix = Util.getRequiredAttribute(keySet, "aliasPrefix", "KeySet" );

        if (keySetName == name and keySetAliasPrefix == aliasPrefix):
          keySetId = keySet;
          break;

  if keySetId is None or len(keySetId) < 1:
    Log.log("Could not find keyset named %(name)s with aliasPrefix of %(alias)s" % { 'name':keySetName, 'alias':keySetAliasPrefix } );

  return keySetId;
