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

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sslconfiggroup.name", objid, "name","SSLConfigGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sslconfiggroup.direction", objid, "direction","SSLConfigGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sslconfiggroup.certificatealias", objid, "certificateAlias","SSLConfigGroup");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

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

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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.sslconfiggroup.name", None));
  Util.addIfNotNone(properties, "direction", roleProperties.optString("websphere.sslconfiggroup.direction", None));
  Util.addIfNotNone(properties, "certificateAlias", roleProperties.optString("websphere.sslconfiggroup.certificatealias", None));
  print "Creating SSLConfigGroup with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("SSLConfigGroup", parentid, properties, None, force);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereManagementScopeRef":
        ManagementScopeRef.create(objid, curjsonobject, "managementScope", force);
      elif currole == "WebSphereSSLConfigRef":
        SSLConfigRef.create(objid, curjsonobject, "sslConfig", force);
  Util.popPathElement('SSLConfigGroup');

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

def doImport(containmentpath, roleName, jsonobject):
  return _doImport(jsonobject, 1);

def _doImport(jsonobject, force):
  # check to see if object exists
  # if it doesn't exist, create it
  # if it does exist, update it
  sslConfigGroupObject = getSSLConfigGroupFromJson(jsonobject);
  if sslConfigGroupObject == None:
    if Util.__removePartialConfig__ == "false":
      securityObjId = Util.getSecurityObjId();
      create(securityObjId, jsonobject, force);
  else:
    if Util.__removePartialConfig__ == "true":
      Util.removePartialApply(sslConfigGroupObject);
    else:
      update(sslConfigGroupObject, jsonobject, force);

def getSSLConfigGroupFromJson(jsonobject):
  # we identify SSLConfigGroup objects by the name attribute and referenced ManagementScope's scopeName
  # from the json, get the SSLConfig's name and managementScope attributes
  # from the SSLConfig's managementScope attribute, get the referenced managementScope's scopeName
  roleProperties = jsonobject.getJSONObject("roleProperties");
  jsonName = roleProperties.optString("websphere.sslconfiggroup.name");
  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;

  # SSLConfigGroup object identifier is in format [name, scopeName]
  identifier = [];
  identifier.append(jsonName);
  identifier.append(jsonScopeName);
  sslConfigGroupObjId = getSSLConfigGroupObjIdFromIdentifier(identifier);
  return sslConfigGroupObjId;

def getSSLConfigGroupObjIdFromIdentifier(identifier):
  targetName = identifier[0];
  targetScopeName = identifier[1];

  # get all SSLConfigGroupss
  sslConfigGroups = Util.getAllObjectsOfType("SSLConfigGroup");
  for sslConfigGroup in sslConfigGroups:
    identifier = getSSLConfigGroupIdentifier(sslConfigGroup);
    foundName = identifier[0];
    foundScopeName = identifier[1];
    if (targetName == foundName) and (targetScopeName == foundScopeName):
      return sslConfigGroup;
  return None;

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


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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  Util.unsetAttribute(objid, "managementScope", "SSLConfigGroup", force);
  Util.unsetAttribute(objid, "sslConfig", "SSLConfigGroup", force);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereManagementScopeRef":
        ManagementScopeRef.create(objid, curjsonobject, "managementScope", force);
      elif currole == "WebSphereSSLConfigRef":
        SSLConfigRef.create(objid, curjsonobject, "sslConfig", force);
  Util.popPathElement('SSLConfigGroup');
