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 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');
