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

__name_att__ = "websphere.userregistryref.name"

def _export(objid, parentrespath, type, realm, name = ""):
  Util.pushPathElement('UserRegistryRef')

  if name == "":
    name = Util.getRequiredAttribute(objid, "realm", "UserRegistry");
  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 UserRegistryRef");
  exportedObject.put("roleName", "WebSphereUserRegistryRef");

  roleProperties = JSONObject();

  # Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.userregistryref.realm", objid, "realm ","UserRegistry");
  # Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.userregistryref.type", objid, "realm ","UserRegistry");
  Util.addToJsonIfNotNone(roleProperties, "websphere.userregistryref.name", name);
  Util.addToJsonIfNotNone(roleProperties, "websphere.userregistryref.type", type);
  Util.addToJsonIfNotNone(roleProperties, "websphere.userregistryref.realm", realm);
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('UserRegistryRef');
  return result;


def doImport(parentid, jsonobject):
  if not jsonobject.has("roleProperties"):
    raise Exception("WebSphereUserRegistryRef resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.userregistryref.type"):
    raise Exception("Resource role properties does not contain websphere.userregistryref.type!");
  #if not roleProperties.has("websphere.userregistryref.realm"):
  #  raise Exception("Resource role properties does not contain websphere.userregistryref.realm!");
  
  type = roleProperties.optString("websphere.userregistryref.type", None);
  targetRealm = roleProperties.optString("websphere.userregistryref.realm", None);
  referencedUserRegistry = None;

  scope = Util.getScope(parentid);
  print "searching for referenced user registry of type " + str(type) + " and realm " + \
         str(targetRealm) + " in scope " + str(scope)

  # get all UserRegistries of the specified type (LocalOSUserRegistry, LDAPUserRegistry, CustomUserRegistry, or WIMUserRegistry)
  userRegistries = Util.getid("/" + type + ":/");
  userRegistries = userRegistries.splitlines();

  for userRegistry in userRegistries:
    # make sure it has the same scope as its parent
    if userRegistry.find(scope) != -1:
      # find the one with the matching realm attribute
      currentRealm = Util.getOptionalAttribute(userRegistry, 'realm', 'UserRegistry');
      if targetRealm == currentRealm:
        referencedUserRegistry = userRegistry;
        print "referenced userRegistry is " + str(userRegistry);
        break;

  if referencedUserRegistry == None or len(referencedUserRegistry) == 0:
    raise Exception("Could not determine the User Registry for User Registry type " + type + " with realm " + targetRealm + ".");
  #no need to setup path elements as the parent must have already done so before invoking the import method
  Util.modify(parentid, [['activeUserRegistry', referencedUserRegistry]]);

