from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from SecureSocketLayer import SecureSocketLayer
from ManagementScopeRef import ManagementScopeRef

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sslconfig.alias", objid, "alias","SSLConfig");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sslconfig.type", objid, "type","SSLConfig");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

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

  managementScope = Util.getOptionalAttribute(objid, 'managementScope', 'SSLConfig');
  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('SSLConfig');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  modifyProperties = [];
  # Initially give alias a "temp" name for creation and then immediately modify to provide real alias name.
  # Workaround for WebSphere error that does not allow creation of SSLConfig objects with the same alias name.
  Util.addIfNotNone(properties, "alias", "tempName");
  Util.addIfNotNone(properties, "type", roleProperties.optString("websphere.sslconfig.type", None));
  print "Creating SSLConfig with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("SSLConfig", parentid, properties, attName);
  Util.addIfNotNone(modifyProperties, "alias", roleProperties.optString("websphere.sslconfig.alias", None));
  print "Modifying SSLConfig with attributes";
  for prop in modifyProperties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  Util.modify(objid, modifyProperties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereSecureSocketLayer":
        SecureSocketLayer.create(objid, curjsonobject);
      elif currole == "WebSphereManagementScopeRef":
        managementScopeId = ManagementScopeRef.create(objid, curjsonobject, "managementScope");
  Util.popPathElement('SSLConfig');

def _doImport(parentid, jsonobject, attName = None):
  # check if the object exists.
  # if it doesn't exist, create it
  # if it does exist, update it
  sslConfigObject = getSSLConfigFromJson(jsonobject);
  modifiedSSLConfig = None;
  if sslConfigObject == None:
    create(parentid, jsonobject, attName);
  else:
    modifiedSSLConfig = update(sslConfigObject, jsonobject);
  # if we modified an existing SSLConfig, return it so that,
  # in Security, we can keep track of existing SSLConfigs and delete any
  # that are no longer in our config data.
  return modifiedSSLConfig;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sslconfig.alias", None), "alias","SSLConfig");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sslconfig.type", None), "type","SSLConfig");
  if len(atts) != 0:
    print "Modifying SSLConfig with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereSecureSocketLayer":
        SecureSocketLayer.create(objid, curjsonobject);
      elif currole == "WebSphereManagementScopeRef":
        ManagementScopeRef.create(objid, curjsonobject, "managementScope");
  Util.popPathElement('SSLConfig');
  return objid;

def getSSLConfigFromJson(jsonobject):
  # we identify SSLConfig objects by the alias attribute and referenced ManagementScope's scopeName
  # from the json, get the SSLConfig's alias and managementScope attributes
  # from the SSLConfig's managementScope attribute, get the referenced managementScope's scopeName
  sslConfigRoleProperties = jsonobject.getJSONObject("roleProperties");
  jsonAlias = sslConfigRoleProperties.optString("websphere.sslconfig.alias");
  jsonScopeName = None;
  foundAlias = None;
  foundScopeName = None;
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereManagementScopeRef":
        msrRoleProperties = curjsonobject.getJSONObject("roleProperties");
        jsonScopeName = msrRoleProperties.optString("websphere.managementscoperef.scopename");
        break;

  # SSLConfig object identifier is in format [alias, scopeName]
  identifier = [];
  identifier.append(jsonAlias);
  identifier.append(jsonScopeName);
  sslConfigObjId = getSSLConfigObjIdFromIdentifier(identifier);
  return sslConfigObjId;

# identifier is a list in format [alias, scopeName]
def getSSLConfigIdentifier(objid):
  identifier = [];
  foundScopeName = "";
  foundAlias = Util.getOptionalAttribute(objid, 'alias', 'SSLConfig');
  managementScope = Util.getOptionalAttribute(objid, 'managementScope', 'SSLConfig');
  if managementScope is not None and len(managementScope) > 0:
    foundScopeName = Util.getOptionalAttribute(managementScope, 'scopeName', 'ManagementScope');
  identifier.append(foundAlias);
  identifier.append(foundScopeName);
  return identifier;

def getSSLConfigObjIdFromIdentifier(identifier):
  targetAlias = identifier[0];
  targetScopeName = identifier[1];

  # get all SSLConfigs
  sslConfigs = Util.getAllObjectsOfType("SSLConfig");
  for sslConfig in sslConfigs:
    identifier = getSSLConfigIdentifier(sslConfig);
    foundAlias = identifier[0];
    foundScopeName = identifier[1];
    if (targetAlias == foundAlias) and (targetScopeName == foundScopeName):
      return sslConfig;
  return None;
