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

__name_att__ = "websphere.listenerport.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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

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

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.listenerport.name", objid, "name","ListenerPort");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.listenerport.connectionfactoryjndiname", objid, "connectionFactoryJNDIName","ListenerPort");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.listenerport.maxmessages", objid, "maxMessages","ListenerPort");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.listenerport.destinationjndiname", objid, "destinationJNDIName","ListenerPort");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.listenerport.maxretries", objid, "maxRetries","ListenerPort");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.listenerport.maxsessions", objid, "maxSessions","ListenerPort");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.listenerport.description", objid, "description","ListenerPort");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  
  stateManagement = Util.getRequiredAttribute(objid, 'stateManagement',"ListenerPort");
  if stateManagement is not None and len(stateManagement) > 0:
    returndict = Util.createTypeFolder(respath, "StateManageable", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, StateManageable._export(stateManagement, currespath, "StateManageable"));    
  
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('ListenerPort');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.listenerport.name"):
    raise Exception("Resource role properties does not contain websphere.listenerport.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 ListenerPort on.");
    objid = create(parentid, jsonobject);
  else:
    update(objid,jsonobject);
  return objid;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.listenerport.name", None));
  Util.addIfNotNone(properties, "connectionFactoryJNDIName", roleProperties.optString("websphere.listenerport.connectionfactoryjndiname", None));
  Util.addIfNotNone(properties, "maxMessages", roleProperties.optString("websphere.listenerport.maxmessages", None));
  Util.addIfNotNone(properties, "destinationJNDIName", roleProperties.optString("websphere.listenerport.destinationjndiname", None));
  Util.addIfNotNone(properties, "maxRetries", roleProperties.optString("websphere.listenerport.maxretries", None));
  Util.addIfNotNone(properties, "maxSessions", roleProperties.optString("websphere.listenerport.maxsessions", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.listenerport.description", None));
  print "Creating ListenerPort with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("ListenerPort", parentid, properties);
  
  stateManagement = Util.getRequiredAttribute(objid, 'stateManagement',"ListenerPort");
  if stateManagement is not None and len(stateManagement) > 0:
    Util.remove(stateManagement);      
  
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");  
      if currole == "WebSphereStateManageable":
        StateManageable.create(objid, curjsonobject);  
  Util.popPathElement('ListenerPort');
        
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.listenerport.name", None), "name","ListenerPort");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.listenerport.connectionfactoryjndiname", None), "connectionFactoryJNDIName","ListenerPort");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.listenerport.maxmessages", None), "maxMessages","ListenerPort");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.listenerport.destinationjndiname", None), "destinationJNDIName","ListenerPort");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.listenerport.maxretries", None), "maxRetries","ListenerPort");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.listenerport.maxsessions", None), "maxSessions","ListenerPort");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.listenerport.description", None), "description","ListenerPort");
  if len(atts) != 0:
    print "Modifying ListenerPort with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  stateManagement = Util.getRequiredAttribute(objid, 'stateManagement',"ListenerPort");
  if stateManagement is not None and len(stateManagement) > 0:
    Util.remove(stateManagement);      
  
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");  
      if currole == "WebSphereStateManageable":
        StateManageable.create(objid, curjsonobject);      

  Util.popPathElement('ListenerPort');
