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

__name_att__ = "websphere.keystore.name";

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keystore.name", objid, "name","KeyStore");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keystore.createstashfileforcms", objid, "createStashFileForCMS","KeyStore");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keystore.initializeatstartup", objid, "initializeAtStartup","KeyStore");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keystore.filebased", objid, "fileBased","KeyStore");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keystore.hostlist", objid, "hostList","KeyStore");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keystore.usage", objid, "usage","KeyStore");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keystore.type", objid, "type","KeyStore");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keystore.provider", objid, "provider","KeyStore");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keystore.customproviderclass", objid, "customProviderClass","KeyStore");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keystore.slot", objid, "slot","KeyStore");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keystore.readonly", objid, "readOnly","KeyStore");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keystore.location", objid, "location","KeyStore");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keystore.password", objid, "password","KeyStore");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keystore.description", objid, "description","KeyStore");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keystore.useforacceleration", objid, "useForAcceleration","KeyStore");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'additionalKeyStoreAttrs',"KeyStore","AdditionalKeyStoreAttrs");

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

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

def doImport(containmentpath, roleName, jsonobject):
  if not jsonobject.has("roleProperties"):
    raise Exception("keystore resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.keystore.name"):
    raise Exception("Resource role properties does not contain websphere.keystore.name!");

  objid = Util.getid(containmentpath);
  if objid == None or len(objid) == 0:
    if Util.__removePartialConfig__ == "false":
      index = containmentpath.rindex('/',0,len(containmentpath)-2)+1;
      parentconpath = containmentpath[0:index];
      parentid = Util.getid(parentconpath);
      if parentid == None or len(parentid) == 0:
        raise Exception("Parent does not exist to create keystore on.");
      objid = create(parentid, jsonobject);
  else:
    # need to compare management scopes because there may be multiple KeyStores with
    # the same name but different scope.
    if jsonobject.has('children'):
      childrenArray = jsonobject.getJSONArray('children');
      for curjsonobject in Util.getHighestChildrenWithRole(childrenArray):
        currole = curjsonobject.getString('roleName');
        if currole == "WebSphereManagementScopeRef":
          msRoleProperties = curjsonobject.getJSONObject("roleProperties");
          targetScopeName = msRoleProperties.optString("websphere.managementscoperef.scopename");
          break;

    # see if more than one were returned
    objIds = objid.splitlines();
    objectToUpdate = "";
    for id in objIds:
      # get management scope
      managementScope = Util.getRequiredAttribute(id, "managementScope", "TrustManager");
      scopeName = Util.getRequiredAttribute(managementScope, "scopeName", "ManagementScope");
      if scopeName == targetScopeName:
        objid = id;
        break;
    if Util.__removePartialConfig__ == "true":
      Util.removePartialApply(objid);
      objid = None;
    else:
      update(objid,jsonobject);
  return objid;

def doImportPartial(containmentpath, roleName, jsonobject):
  return doImport(containmentpath, roleName, jsonobject);

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.keystore.name", None));
  Util.addIfNotNone(properties, "createStashFileForCMS", roleProperties.optString("websphere.keystore.createstashfileforcms", None));
  Util.addIfNotNone(properties, "initializeAtStartup", roleProperties.optString("websphere.keystore.initializeatstartup", None));
  Util.addIfNotNone(properties, "fileBased", roleProperties.optString("websphere.keystore.filebased", None));
  Util.addIfNotNone(properties, "hostList", roleProperties.optString("websphere.keystore.hostlist", None));
  Util.addIfNotNone(properties, "usage", roleProperties.optString("websphere.keystore.usage", None));
  Util.addIfNotNone(properties, "type", roleProperties.optString("websphere.keystore.type", None));
  Util.addIfNotNone(properties, "provider", roleProperties.optString("websphere.keystore.provider", None));
  Util.addIfNotNone(properties, "customProviderClass", roleProperties.optString("websphere.keystore.customproviderclass", None));
  Util.addIfNotNone(properties, "slot", roleProperties.optString("websphere.keystore.slot", None));
  Util.addIfNotNone(properties, "readOnly", roleProperties.optString("websphere.keystore.readonly", None));
  Util.addIfNotNone(properties, "location", roleProperties.optString("websphere.keystore.location", None));
  Util.addIfNotNone(properties, "password", roleProperties.optString("websphere.keystore.password", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.keystore.description", None));
  Util.addIfNotNone(properties, "useForAcceleration", roleProperties.optString("websphere.keystore.useforacceleration", None));
  print "Creating KeyStore with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("KeyStore", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      attName = None;
      currpath = curjsonobject.getString('path');
      lastSlashIndex = currpath.rindex('/');
      nextToLastSlashIndex = currpath.rindex('/', 0, lastSlashIndex - 1);
      foldername = currpath[nextToLastSlashIndex+1:lastSlashIndex];
      if (foldername.find(Util.getTypeFoldername('AdditionalKeyStoreAttrs')) > -1):
        attName = 'additionalKeyStoreAttrs';
      propertObject = 0;
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole, attName);
      if (propertyObject == 0):
        if currole == "WebSphereManagementScopeRef":
          ManagementScopeRef.create(objid, curjsonobject, "managementScope");
  Util.popPathElement('KeyStore');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keystore.name", None), "name","KeyStore");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keystore.createstashfileforcms", None), "createStashFileForCMS","KeyStore");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keystore.initializeatstartup", None), "initializeAtStartup","KeyStore");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keystore.filebased", None), "fileBased","KeyStore");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keystore.hostlist", None), "hostList","KeyStore");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keystore.usage", None), "usage","KeyStore");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keystore.type", None), "type","KeyStore");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keystore.provider", None), "provider","KeyStore");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keystore.customproviderclass", None), "customProviderClass","KeyStore");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keystore.slot", None), "slot","KeyStore");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keystore.readonly", None), "readOnly","KeyStore");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keystore.location", None), "location","KeyStore");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keystore.password", None), "password","KeyStore");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keystore.description", None), "description","KeyStore");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keystore.useforacceleration", None), "useForAcceleration","KeyStore");
  if len(atts) != 0:
    print "Modifying KeyStore with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Property.removeProperties(objid, 'additionalKeyStoreAttrs',"KeyStore");

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      attName = None;
      currpath = curjsonobject.getString('path');
      lastSlashIndex = currpath.rindex('/');
      nextToLastSlashIndex = currpath.rindex('/', 0, lastSlashIndex - 1);
      foldername = currpath[nextToLastSlashIndex+1:lastSlashIndex];
      if (foldername.find(Util.getTypeFoldername('AdditionalKeyStoreAttrs')) > -1):
        attName = 'additionalKeyStoreAttrs';
      propertObject = 0;
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole, attName);
      if (propertyObject == 0):
        if currole == "WebSphereManagementScopeRef":
          ManagementScopeRef.create(objid, curjsonobject, "managementScope");
  Util.popPathElement('KeyStore');

def find(parentid, jsonobject):

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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has('websphere.keystore.name'):
    raise Exception("KeyStore resource has no property named websphere.keystore.name!");
  if not roleProperties.has('websphere.keystore.location'):
    raise Exception("KeyStore resource has no property named websphere.keystore.location!");

  keyStoreName = roleProperties.getString('websphere.keystore.name');
  keyStoreLocation = roleProperties.getString('websphere.keystore.location');

  keyStoreId = None;
  keyStores = Util.getid("/KeyStore:/").splitlines();
  if len(keyStores) > 0:
    for keyStore in keyStores:
      if len(keyStore) > 0:
        name = Util.getRequiredAttribute(keyStore, "name", "KeyStore" );
        location = Util.getRequiredAttribute(keyStore, "location", "KeyStore" );

        if (keyStoreName == name and keyStoreLocation == location):
          keyStoreId = keyStore;
          break;

  if keyStoreId is None or len(keyStoreId) < 1:
    Log.log("Could not find keystore named %(name)s with location of %(loc)s" % { 'name':keyStoreName, 'loc':keyStoreLocation } );

  return keyStoreId;
