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

__name_att__ = "websphere.jmsprovider.name"

def export(objid, parentcontainmentpath, parentrespath):

  name = Util.getRequiredAttribute(objid, "name", 'JMSProvider');

  containmentpath = "%(parentconpath)sJMSProvider:%(name)s/" % {'parentconpath':parentcontainmentpath, 'name':name }
  if not containmentpath.startswith("/"):
    containmentpath = "/" + containmentpath;

  dict = _export(objid, parentrespath, containmentpath);
  dict['conpath'] = containmentpath;
  return dict

def _export(objid, parentrespath, parentcontainmentpath):
  Util.pushPathElement('JMSProvider')

  name = Util.getRequiredAttribute(objid, "name", 'JMSProvider');


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jmsprovider.name", objid, "name","JMSProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jmsprovider.externalproviderurl", objid, "externalProviderURL","JMSProvider");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.jmsprovider.classpath", objid, "classpath","JMSProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jmsprovider.providertype", objid, "providerType","JMSProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jmsprovider.supportsasf", objid, "supportsASF","JMSProvider");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.jmsprovider.nativepath", objid, "nativepath","JMSProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jmsprovider.description", objid, "description","JMSProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jmsprovider.externalinitialcontextfactory", objid, "externalInitialContextFactory","JMSProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jmsprovider.isolatedclassloader", objid, "isolatedClassLoader","JMSProvider");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  # get all MQQueue objects for this JMSProvider
  mqQueues = Util.getid(parentcontainmentpath + "MQQueue:/").splitlines();
  i = 0;
  for mqQueue in mqQueues:
      if len(mqQueue) > 0:
        returndict = Util.createTypeFolder(respath, "MQQueue", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        Util.addAllFromExport(extraObjects, MQQueue._export(mqQueue, currespath, "MQQueue%s" % i));
        i = i + 1;

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

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.jmsprovider.name"):
    raise Exception("Resource role properties does not contain websphere.jmsprovider.name!");

  objid = Util.getid(containmentpath);
  if objid == None or len(objid) == 0:
    index = containmentpath.rindex('/',0,len(containmentpath)-2)+1;
    parentconpath = containmentpath[0:index];
    parentid = Util.getid(parentconpath);
    if parentid == None or len(parentid) == 0:
      raise Exception("Parent does not exist to create JMSProvider on.");
    objid = create(parentid, jsonobject);
  else:
    update(objid,jsonobject,containmentpath);
  return objid;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  if not roleProperties.has("websphere.jmsprovider.name"):
    raise Exception("Resource role properties does not contain websphere.jmsprovider.name!");

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.jmsprovider.name", None));
  Util.addIfNotNone(properties, "externalProviderURL", roleProperties.optString("websphere.jmsprovider.externalproviderurl", None));
  Util.addPathProperty(properties, "classpath", roleProperties.optString("websphere.jmsprovider.classpath", None));
  Util.addIfNotNone(properties, "providerType", roleProperties.optString("websphere.jmsprovider.providertype", None));
  Util.addIfNotNone(properties, "supportsASF", roleProperties.optString("websphere.jmsprovider.supportsasf", None));
  Util.addPathProperty(properties, "nativepath", roleProperties.optString("websphere.jmsprovider.nativepath", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.jmsprovider.description", None));
  Util.addIfNotNone(properties, "externalInitialContextFactory", roleProperties.optString("websphere.jmsprovider.externalinitialcontextfactory", None));
  Util.addIfNotNone(properties, "isolatedClassLoader", roleProperties.optString("websphere.jmsprovider.isolatedclassloader", None));
  print "Creating JMSProvider with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("JMSProvider", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereMQQueue":
        MQQueue.create(objid, curjsonobject);

  Util.popPathElement('JMSProvider');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  if not roleProperties.has("websphere.jmsprovider.name"):
    raise Exception("Resource role properties does not contain websphere.jmsprovider.name!");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jmsprovider.name", None), "name","JMSProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jmsprovider.externalproviderurl", None), "externalProviderURL","JMSProvider");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.jmsprovider.classpath", None), "classpath","JMSProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jmsprovider.providertype", None), "providerType","JMSProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jmsprovider.supportsasf", None), "supportsASF","JMSProvider");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.jmsprovider.nativepath", None), "nativepath","JMSProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jmsprovider.description", None), "description","JMSProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jmsprovider.externalinitialcontextfactory", None), "externalInitialContextFactory","JMSProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jmsprovider.isolatedclassloader", None), "isolatedClassLoader","JMSProvider");
  if len(atts) != 0:
    print "Modifying JMSProvider with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  mqQueues = Util.getid(parentcontainmentpath + "MQQueue:/").splitlines();
  if mqQueues != None and len(mqQueues) > 0:
    for mqQueue in mqQueues:
      if len(mqQueue) > 0:
        Util.remove(mqQueue);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereMQQueue":
        MQQueue.create(objid, curjsonobject);

  Util.popPathElement('JMSProvider');
