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

__name_att__ = "websphere.foreigncell.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.foreigncell.name", objid, "name","ForeignCell");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  bootstrapAddress = Util.getOptionalAttribute(objid, 'bootstrapAddress', "CellManager");
  if (bootstrapAddress != None):
    returndict = Util.createTypeFolder(respath, "EndPoint", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, EndPoint._export(bootstrapAddress, currespath, "bootstrapAddress"));

  i = 0;
  endpoints = Util.parseConfigIdListAttribute(objid, 'bootstrapAddresses', "ForeignCell");
  for endpoint in endpoints:
    if len(endpoint) > 0:
      returndict = Util.createTypeFolder(respath, "EndPoint", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, EndPoint._export(endpoint, currespath, "bootstrapAddress%s" % i));
      i = i + 1

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



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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereEndPoint":
        bootstrapAddresses = Util.getOptionalAttribute(objid, 'bootstrapAddresses', "ForeignCell");
        if (bootstrapAddresses != None):
          EndPoint.create(objid, curjsonobject, 'bootstrapAddresses');
        else:
          oep = Util.getRequiredAttribute(objid, "bootstrapAddress", "NodeAgent");
          EndPoint.update(oep, curjsonobject);
  Util.popPathElement('ForeignCell');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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

  endpoints = Util.parseConfigIdListAttribute(objid, 'bootstrapAddresses', "ForeignCell");
  for endpoint in endpoints:
    if len(endpoint) > 0:
      Util.remove(endpoint);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereEndPoint":
        bootstrapAddresses = Util.getOptionalAttribute(objid, 'bootstrapAddresses', "ForeignCell");
        if (bootstrapAddresses != None):
          EndPoint.create(objid, curjsonobject, 'bootstrapAddresses');
        else:
          oep = Util.getRequiredAttribute(objid, "bootstrapAddress", "NodeAgent");
          EndPoint.update(oep, curjsonobject);

  Util.popPathElement('ForeignCell');
