from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from SIBAuthUser import SIBAuthUser;
from SIBAuthAlias import SIBAuthAlias;
from SIBAuthDefault import SIBAuthDefault;
from SIBAuthGroup import SIBAuthGroup;
from SIBAuthBusConnect import SIBAuthBusConnect;
from SIBAuthForeignBus import SIBAuthForeignBus;
from SIBAuthForeignDestination import SIBAuthForeignDestination;
from SIBAuthWebService import SIBAuthWebService;
from SIBAuthPort import SIBAuthPort;
from SIBAuthTopicSpace import SIBAuthTopicSpace;

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

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

  i = 0;
  sibAuthUsers = Util.parseConfigIdListAttribute(objid, 'user',"SIBAuthSpace");
  for sibAuthUser in sibAuthUsers:
    if len(sibAuthUser) > 0:
      returndict = Util.createTypeFolder(respath, "SIBAuthUser", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, SIBAuthUser._export(sibAuthUser, currespath, "SIBAuthUser%s" % i));
      i = i + 1;

  groups = Util.parseConfigIdListAttribute(objid, 'group',"SIBAuthSpace");
  for group in groups:
    if len(group) > 0:
      returndict = Util.createTypeFolder(respath, "SIBAuthGroup", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, SIBAuthGroup._export(group, currespath));

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

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

  i = 0;
  foreignBuses = Util.parseConfigIdListAttribute(objid, 'foreignBus',"SIBAuthSpace");
  for foreignBus in foreignBuses:
    if len(foreignBus) > 0:
      returndict = Util.createTypeFolder(respath, "SIBAuthSIBAuthForeignBus", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, SIBAuthForeignBus._export(foreignBus, currespath, "SIBAuthForeignBus%s" % i));
      i = i + 1;

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

  i = 0;
  j = 0;
  queues = Util.parseConfigIdListAttribute(objid, 'queue',"SIBAuthSpace");
  for queue in queues:
    if len(queue) > 0:
      if queue.find("#SIBAuthWebService_") > 0:
        returndict = Util.createTypeFolder(respath, "SIBAuthWebService", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        Util.addAllFromExport(extraObjects, SIBAuthWebService._export(queue, currespath, "SIBAuthWebService%s" % i));
        i = i + 1;
      elif queue.find("#SIBAuthPort_") > 0:
        returndict = Util.createTypeFolder(respath, "SIBAuthPort", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        Util.addAllFromExport(extraObjects, SIBAuthPort._export(queue, currespath, "SIBAuthPort%s" % j));
        j = j + 1;

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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  print "Creating SIBAuthSpace with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("SIBAuthSpace", parentid, properties);
  
  sibAuthUsers = Util.parseConfigIdListAttribute(objid, 'user',"SIBAuthSpace");
  for sibAuthUser in sibAuthUsers:
    if len(sibAuthUser) > 0:
      Util.remove(sibAuthUser);

  groups = Util.parseConfigIdListAttribute(objid, 'group',"SIBAuthSpace");
  for group in groups:
    if len(group) > 0:
      Util.remove(group);

  # SIBAuthGroups and SIBAuthUsers must be created first because other objects may reference them
  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    for curjsonobject in children[:]:
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereSIBAuthGroup":
        SIBAuthGroup.create(objid, curjsonobject);
        children.remove(curjsonobject);
      elif currole == "WebSphereSIBAuthUser":
        SIBAuthUser.create(objid, curjsonobject);
        children.remove(curjsonobject);
    
  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    for curjsonobject in children[:]:
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereSIBAuthAlias":
        SIBAuthAlias.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthDefault":
        SIBAuthDefault.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthBusConnect":
        SIBAuthBusConnect.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthForeignBus":
        SIBAuthForeignBus.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthForeignDestination":
        SIBAuthForeignDestination.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthWebService":
        SIBAuthWebService.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthPort":
        SIBAuthPort.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthTopicSpace":
        SIBAuthTopicSpace.create(objid, curjsonobject);
  Util.popPathElement('SIBAuthSpace');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  if len(atts) != 0:
    print "Modifying SIBAuthSpace with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  aliases = Util.parseConfigIdListAttribute(objid, 'alias',"SIBAuthSpace");
  for alias in aliases:
    if len(alias) > 0:
      Util.remove(alias);

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

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

  foreignBuses = Util.parseConfigIdListAttribute(objid, 'foreignBus',"SIBAuthSpace");
  for foreignBus in foreignBuses:
    if len(foreignBus) > 0:
      Util.remove(foreignBus);

  foreignDestinations = Util.parseConfigIdListAttribute(objid, 'foreignDestination',"SIBAuthSpace");
  for foreignDestination in foreignDestinations:
    if len(foreignDestination) > 0:
      Util.remove(foreignDestination);

  queues = Util.parseConfigIdListAttribute(objid, 'queue',"SIBAuthSpace");
  for queue in queues:
    if len(queue) > 0:
      Util.remove(queue);

  topicSpaces = Util.parseConfigIdListAttribute(objid, 'topicSpace',"SIBAuthSpace");
  for topicSpace in topicSpaces:
    if len(topicSpace) > 0:
      Util.remove(topicSpace);

  # probably should remove SIBAuthUsers and SIBAuthGroups last due to references
  sibAuthUsers = Util.parseConfigIdListAttribute(objid, 'user',"SIBAuthSpace");
  for sibAuthUser in sibAuthUsers:
    if len(sibAuthUser) > 0:
      Util.remove(sibAuthUser);

  groups = Util.parseConfigIdListAttribute(objid, 'group',"SIBAuthSpace");
  for group in groups:
    if len(group) > 0:
      Util.remove(group);

  # SIBAuthGroups and SIBAuthUsers must be created first because other objects may reference them
  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    for curjsonobject in children[:]:
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereSIBAuthGroup":
        SIBAuthGroup.create(objid, curjsonobject);
        children.remove(curjsonobject);
      elif currole == "WebSphereSIBAuthUser":
        SIBAuthUser.create(objid, curjsonobject);
        children.remove(curjsonobject);

  if jsonobject.has('children'):
    for curjsonobject in children[:]:
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereSIBAuthAlias":
        SIBAuthAlias.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthDefault":
        SIBAuthDefault.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthBusConnect":
        SIBAuthBusConnect.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthForeignBus":
        SIBAuthForeignBus.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthForeignDestination":
        SIBAuthForeignDestination.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthWebService":
        SIBAuthWebService.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthPort":
        SIBAuthPort.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthTopicSpace":
        SIBAuthTopicSpace.create(objid, curjsonobject);
  Util.popPathElement('SIBAuthSpace');

def getSIBAuthSpaces(objid):
  sibAuthSpaces = Util.getAssociatedObjects(objid, "SIBAuthSpace");
  return sibAuthSpaces;         
