from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from NodeGroupMapping import NodeGroupMapping;
from Security import Security
from utilities import Util
from Property import Property

__name_att__ = "websphere.node"

def export(objid, parentcontainmentpath, parentrespath):

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

  containmentpath = "%(parentconpath)sNode:%(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('Node')

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.node.shortname", objid, "shortName","Node");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.node", objid, "name","Node");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.node.maxfilepermissionforapps", objid, "maxFilePermissionForApps","Node");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.node.discoveryprotocol", objid, "discoveryProtocol","Node");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.node.hostname", objid, "hostName","Node");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  typeFolders = {};
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"Node");
  Util.addAllFromExport(extraObjects, NodeGroupMapping._export(objid, respath));

  secfolderretdict = Util.createTypeFolder(respath, "Security", typeFolders);
  secresfolpath = secfolderretdict['path'];
  if secfolderretdict.has_key('object'):
    Util.addFromExport(extraObjects, secfolderretdict['object']);

  Util.addAllFromExport(extraObjects, Security._export(objid, secresfolpath, "Security"));
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('Node');
  return result;

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

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

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

  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 Node on.");
    objid = create(parentid, jsonobject);
  else:
    update(objid,jsonobject);
  return objid;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "shortName", roleProperties.optString("websphere.node.shortname", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.node", None));
  Util.addIfNotNone(properties, "maxFilePermissionForApps", roleProperties.optString("websphere.node.maxfilepermissionforapps", None));
  Util.addIfNotNone(properties, "discoveryProtocol", roleProperties.optString("websphere.node.discoveryprotocol", None));
  Util.addIfNotNone(properties, "hostName", roleProperties.optString("websphere.node.hostname", None));
  print "Creating Node with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("Node", parentid, properties);

  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    for curjsonobject in children:
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereNodeGroupMapping":
        NodeGroupMapping.doImport(objid, curjsonobject);
      elif currole == "WebSphereSecurity":
        Security.update(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.node.shortname", None), "shortName","Node");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.node", None), "name","Node");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.node.maxfilepermissionforapps", None), "maxFilePermissionForApps","Node");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.node.discoveryprotocol", None), "discoveryProtocol","Node");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.node.hostname", None), "hostName","Node");
  if len(atts) != 0:
    print "Modifying Node with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Property.removeProperties(objid, 'properties',"Node");

  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    for curjsonobject in children:
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereNodeGroupMapping":
        NodeGroupMapping.doImport(objid, curjsonobject);
      elif currole == "WebSphereSecurity":
        Security.update(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);

  Util.popPathElement('Node');
