from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from Property import Property
from EndPoint import EndPoint
from LDAPSearchFilter import LDAPSearchFilter

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ldapuserregistry.sslconfig", objid, "sslConfig","LDAPUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ldapuserregistry.searchtimeout", objid, "searchTimeout","LDAPUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ldapuserregistry.type", objid, "type","LDAPUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ldapuserregistry.ignorecase", objid, "ignoreCase","LDAPUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ldapuserregistry.bindpassword", objid, "bindPassword","LDAPUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ldapuserregistry.basedn", objid, "baseDN","LDAPUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ldapuserregistry.useregistryrealm", objid, "useRegistryRealm","LDAPUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ldapuserregistry.realm", objid, "realm","LDAPUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ldapuserregistry.serverpassword", objid, "serverPassword","LDAPUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ldapuserregistry.serverid", objid, "serverId","LDAPUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ldapuserregistry.reuseconnection", objid, "reuseConnection","LDAPUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ldapuserregistry.useregistryserverid", objid, "useRegistryServerId","LDAPUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ldapuserregistry.sslenabled", objid, "sslEnabled","LDAPUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ldapuserregistry.limit", objid, "limit","LDAPUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ldapuserregistry.primaryadminid", objid, "primaryAdminId","LDAPUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ldapuserregistry.binddn", objid, "bindDN","LDAPUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ldapuserregistry.monitorinterval", objid, "monitorInterval","LDAPUserRegistry");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  i = 0;
  hosts = Util.parseConfigIdListAttribute(objid, 'hosts', "LDAPUserRegistry");
  for host in hosts:
    if len(host) > 0:
      returndict = Util.createTypeFolder(respath, "EndPoint", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, EndPoint._export(host, currespath, "Host%s" % i));
      i = i + 1;

  searchFilter = Util.getOptionalAttribute(objid, 'searchFilter', 'LDAPUserRegistry');
  if searchFilter is not None and len(searchFilter) > 0:
    returndict = Util.createTypeFolder(respath, "LDAPSearchFilter", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, LDAPSearchFilter._export(searchFilter, currespath, "LDAP Search Filter"));

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"LDAPUserRegistry");
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('LDAPUserRegistry');
  return result;

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

def doImport(containmentpath, roleName, jsonobject):

  ldap = Util.getid(containmentpath);

  if ldap == None or ldap == "":
    if Util.__removePartialConfig__ == "false":
      index = containmentpath.rindex('/',0,len(containmentpath)-2)+1;
      parentconpath = containmentpath[0:index];
      parentid = Util.getid(parentconpath);
      ldap = create(parentid, jsonobject);
  else:
    if Util.__removePartialConfig__ == "true":
      Util.removePartialApply(ldap);
      ldap = None;
    else:
      update(ldap, jsonobject);
  return ldap;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "sslConfig", roleProperties.optString("websphere.ldapuserregistry.sslconfig", None));
  Util.addIfNotNone(properties, "searchTimeout", roleProperties.optString("websphere.ldapuserregistry.searchtimeout", None));
  Util.addIfNotNone(properties, "type", roleProperties.optString("websphere.ldapuserregistry.type", None));
  Util.addIfNotNone(properties, "ignoreCase", roleProperties.optString("websphere.ldapuserregistry.ignorecase", None));
  Util.addIfNotNone(properties, "bindPassword", roleProperties.optString("websphere.ldapuserregistry.bindpassword", None));
  Util.addIfNotNone(properties, "baseDN", roleProperties.optString("websphere.ldapuserregistry.basedn", None));
  Util.addIfNotNone(properties, "useRegistryRealm", roleProperties.optString("websphere.ldapuserregistry.useregistryrealm", None));
  Util.addIfNotNone(properties, "realm", roleProperties.optString("websphere.ldapuserregistry.realm", None));
  Util.addIfNotNone(properties, "serverPassword", roleProperties.optString("websphere.ldapuserregistry.serverpassword", None));
  Util.addIfNotNone(properties, "serverId", roleProperties.optString("websphere.ldapuserregistry.serverid", None));
  Util.addIfNotNone(properties, "reuseConnection", roleProperties.optString("websphere.ldapuserregistry.reuseconnection", None));
  Util.addIfNotNone(properties, "useRegistryServerId", roleProperties.optString("websphere.ldapuserregistry.useregistryserverid", None));
  Util.addIfNotNone(properties, "sslEnabled", roleProperties.optString("websphere.ldapuserregistry.sslenabled", None));
  Util.addIfNotNone(properties, "limit", roleProperties.optString("websphere.ldapuserregistry.limit", None));
  Util.addIfNotNone(properties, "primaryAdminId", roleProperties.optString("websphere.ldapuserregistry.primaryadminid", None));
  Util.addIfNotNone(properties, "bindDN", roleProperties.optString("websphere.ldapuserregistry.binddn", None));
  Util.addIfNotNone(properties, "monitorInterval", roleProperties.optString("websphere.ldapuserregistry.monitorinterval", None));
  print "Creating LDAPUserRegistry with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("LDAPUserRegistry", parentid, properties);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereEndPoint":
        EndPoint.create(objid, curjsonobject);
      elif currole == "WebSphereLDAPSearchFilter":
        LDAPSearchFilter.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('LDAPUserRegistry');

def update(parentid,jsonobject):
  Util.pushPathElement('LDAPUserRegistry')
  objid = getLDAPUserRegistry(parentid)[0];

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ldapuserregistry.sslconfig", None), "sslConfig","LDAPUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ldapuserregistry.searchtimeout", None), "searchTimeout","LDAPUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ldapuserregistry.type", None), "type","LDAPUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ldapuserregistry.ignorecase", None), "ignoreCase","LDAPUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ldapuserregistry.bindpassword", None), "bindPassword","LDAPUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ldapuserregistry.basedn", None), "baseDN","LDAPUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ldapuserregistry.useregistryrealm", None), "useRegistryRealm","LDAPUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ldapuserregistry.realm", None), "realm","LDAPUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ldapuserregistry.serverpassword", None), "serverPassword","LDAPUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ldapuserregistry.serverid", None), "serverId","LDAPUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ldapuserregistry.reuseconnection", None), "reuseConnection","LDAPUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ldapuserregistry.useregistryserverid", None), "useRegistryServerId","LDAPUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ldapuserregistry.sslenabled", None), "sslEnabled","LDAPUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ldapuserregistry.limit", None), "limit","LDAPUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ldapuserregistry.primaryadminid", None), "primaryAdminId","LDAPUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ldapuserregistry.binddn", None), "bindDN","LDAPUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.ldapuserregistry.monitorinterval", None), "monitorInterval","LDAPUserRegistry");
  if len(atts) != 0:
    print "Modifying LDAPUserRegistry with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  hosts = Util.parseConfigIdListAttribute(objid, 'hosts', "LDAPUserRegistry");
  for host in hosts:
    Util.remove(host);

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

  Property.removeProperties(objid, 'properties',"LDAPUserRegistry");

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereEndPoint":
        EndPoint.create(objid, curjsonobject);
      elif currole == "WebSphereLDAPSearchFilter":
        LDAPSearchFilter.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('LDAPUserRegistry');

def getLDAPUserRegistry(objid):
  ldapUserRegistry = Util.getAssociatedObjects(objid, "LDAPUserRegistry");
  return ldapUserRegistry;

