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

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customuserregistry.useregistryrealm", objid, "useRegistryRealm","CustomUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customuserregistry.serverpassword", objid, "serverPassword","CustomUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customuserregistry.primaryadminid", objid, "primaryAdminId","CustomUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customuserregistry.useregistryserverid", objid, "useRegistryServerId","CustomUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customuserregistry.limit", objid, "limit","CustomUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customuserregistry.customregistryclassname", objid, "customRegistryClassName","CustomUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customuserregistry.serverid", objid, "serverId","CustomUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customuserregistry.realm", objid, "realm","CustomUserRegistry");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customuserregistry.ignorecase", objid, "ignoreCase","CustomUserRegistry");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"CustomUserRegistry");
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('CustomUserRegistry');
  return result;

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

def doImport(containmentpath, roleName, jsonobject):

  customUserReg = Util.getid(containmentpath);

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "useRegistryRealm", roleProperties.optString("websphere.customuserregistry.useregistryrealm", None));
  Util.addIfNotNone(properties, "serverPassword", roleProperties.optString("websphere.customuserregistry.serverpassword", None));
  Util.addIfNotNone(properties, "primaryAdminId", roleProperties.optString("websphere.customuserregistry.primaryadminid", None));
  Util.addIfNotNone(properties, "useRegistryServerId", roleProperties.optString("websphere.customuserregistry.useregistryserverid", None));
  Util.addIfNotNone(properties, "limit", roleProperties.optString("websphere.customuserregistry.limit", None));
  Util.addIfNotNone(properties, "customRegistryClassName", roleProperties.optString("websphere.customuserregistry.customregistryclassname", None));
  Util.addIfNotNone(properties, "serverId", roleProperties.optString("websphere.customuserregistry.serverid", None));
  Util.addIfNotNone(properties, "realm", roleProperties.optString("websphere.customuserregistry.realm", None));
  Util.addIfNotNone(properties, "ignoreCase", roleProperties.optString("websphere.customuserregistry.ignorecase", None));
  print "Creating CustomUserRegistry with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("CustomUserRegistry", parentid, properties);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('CustomUserRegistry');

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];

  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customuserregistry.useregistryrealm", None), "useRegistryRealm","CustomUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customuserregistry.serverpassword", None), "serverPassword","CustomUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customuserregistry.primaryadminid", None), "primaryAdminId","CustomUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customuserregistry.useregistryserverid", None), "useRegistryServerId","CustomUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customuserregistry.limit", None), "limit","CustomUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customuserregistry.customregistryclassname", None), "customRegistryClassName","CustomUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customuserregistry.serverid", None), "serverId","CustomUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customuserregistry.realm", None), "realm","CustomUserRegistry");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customuserregistry.ignorecase", None), "ignoreCase","CustomUserRegistry");
  if len(atts) != 0:
    print "Modifying CustomUserRegistry with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('CustomUserRegistry');

def getCustomUserRegistry(objid):
  #assumption that can only return one
  customUserRegistry = Util.getAssociatedObjects(objid, "CustomUserRegistry");
  return customUserRegistry;
