from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from SIBAuthTopic import SIBAuthTopic;
from SIBAuthTopicSpaceBase import SIBAuthTopicSpaceBase;
from SIBAuthTopicSpaceRoot import SIBAuthTopicSpaceRoot;

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibauthtopicspace.inheritdefaults", objid, "inheritDefaults","SIBAuthTopicSpace");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.sibauthtopicspace.identifier", objid, "identifier","SIBAuthTopicSpace");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

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

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

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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "inheritDefaults", roleProperties.optString("websphere.sibauthtopicspace.inheritdefaults", None));
  Util.addIfNotNone(properties, "identifier", roleProperties.optString("websphere.sibauthtopicspace.identifier", None));
  print "Creating SIBAuthTopicSpace with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("SIBAuthTopicSpace", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereSIBAuthTopic":
        SIBAuthTopic.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthTopicSpaceBase":
        SIBAuthTopicSpaceBase.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthTopicSpaceRoot":
        SIBAuthTopicSpaceRoot.create(objid, curjsonobject);

  Util.popPathElement('SIBAuthTopicSpace');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibauthtopicspace.inheritdefaults", None), "inheritDefaults","SIBAuthTopicSpace");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.sibauthtopicspace.identifier", None), "identifier","SIBAuthTopicSpace");
  if len(atts) != 0:
    print "Modifying SIBAuthTopicSpace with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  topics = Util.parseConfigIdListAttribute(objid, 'topic',"SIBAuthTopicSpace");
  for topic in topic:
    if len(topic) > 0:
      Util.remove(topic);

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

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereSIBAuthTopic":
        SIBAuthTopic.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthTopicSpaceBase":
        SIBAuthTopicSpaceBase.create(objid, curjsonobject);
      elif currole == "WebSphereSIBAuthTopicSpaceRoot":
        SIBAuthTopicSpaceRoot.create(objid, curjsonobject); 

  Util.popPathElement('SIBAuthTopicSpace');
