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

__name_att__ = "websphere.j2eeresourceproperty.name"

def export(objid, parentcontainmentpath, parentrespath):

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

  containmentpath = "%(parentconpath)sJ2EEResourceProperty:%(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, name = ""):
  Util.pushPathElement('J2EEResourceProperty')

  if name == None or len(name) == 0:
    name = Util.getRequiredAttribute(objid, "name", 'J2EEResourceProperty');

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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2eeresourceproperty.name", objid, "name","J2EEResourceProperty");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2eeresourceproperty.type", objid, "type","J2EEResourceProperty");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2eeresourceproperty.description", objid, "description","J2EEResourceProperty");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2eeresourceproperty.confidential", objid, "confidential","J2EEResourceProperty");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2eeresourceproperty.value", objid, "value","J2EEResourceProperty");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2eeresourceproperty.supportsdynamicupdates", objid, "supportsDynamicUpdates","J2EEResourceProperty");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2eeresourceproperty.required", objid, "required","J2EEResourceProperty");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.j2eeresourceproperty.ignore", objid, "ignore","J2EEResourceProperty");

  #This is to filter out any strange extra whitespace characters such as \t and \n
  typeString = roleProperties.optString("websphere.j2eeresourceproperty.type");
  typeString = re.sub('\s+', ' ', typeString);
  typeString = typeString.strip();
  roleProperties.put("websphere.j2eeresourceproperty.type", typeString);

  descriptionString = roleProperties.optString("websphere.j2eeresourceproperty.description");
  descriptionString = descriptionString.strip();
  roleProperties.put("websphere.j2eeresourceproperty.description", descriptionString);

  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('J2EEResourceProperty');
  return result;


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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.j2eeresourceproperty.name"):
    raise Exception("Resource role properties does not contain websphere.j2eeresourceproperty.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 J2EEResourceProperty on. Parent containment path is " + parentconpath);
    objid = create(parentid, jsonobject);
  else:
    update(objid,jsonobject);
  return objid;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.j2eeresourceproperty.name", None));
  # A common value for type is "[Ljava.lang.String;"
  # The leading bracket will cause Apply to fail with a IllegalArgumentException.
  # The workaround is to add a blank space before the bracket.
  # For more info, see http://www-01.ibm.com/support/docview.wss?uid=swg21587193
  type = roleProperties.optString("websphere.j2eeresourceproperty.type", None)
  if type is not None and type.startswith("["):
    type = " " + type;
  Util.addIfNotNone(properties, "type", type);
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.j2eeresourceproperty.description", None));
  Util.addIfNotNone(properties, "confidential", roleProperties.optString("websphere.j2eeresourceproperty.confidential", "false"));
  Util.addIfNotNone(properties, "value", roleProperties.optString("websphere.j2eeresourceproperty.value", None));
  Util.addIfNotNone(properties, "supportsDynamicUpdates", roleProperties.optString("websphere.j2eeresourceproperty.supportsdynamicupdates", "false"));
  Util.addIfNotNone(properties, "required", roleProperties.optString("websphere.j2eeresourceproperty.required", "false"));
  Util.addIfNotNone(properties, "ignore", roleProperties.optString("websphere.j2eeresourceproperty.ignore", "false"));
  print "Creating J2EEResourceProperty with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("J2EEResourceProperty", parentid, properties);
  Util.popPathElement('J2EEResourceProperty');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2eeresourceproperty.name", None), "name","J2EEResourceProperty");
  # A common value for type is "[Ljava.lang.String;"
  # The leading bracket will cause Apply to fail with a IllegalArgumentException.
  # The workaround is to add a blank space before the bracket.
  # For more info, see http://www-01.ibm.com/support/docview.wss?uid=swg21587193
  type = roleProperties.optString("websphere.j2eeresourceproperty.type", None)
  if type.startswith("["):
    type = " " + type;
  Util.addAttIfChanged(objid, atts, type, "type","J2EEResourceProperty");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2eeresourceproperty.description", None), "description","J2EEResourceProperty");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2eeresourceproperty.confidential", "false"), "confidential","J2EEResourceProperty");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2eeresourceproperty.value", None), "value","J2EEResourceProperty");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2eeresourceproperty.supportsdynamicupdates", "false"), "supportsDynamicUpdates","J2EEResourceProperty");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2eeresourceproperty.required", "false"), "required","J2EEResourceProperty");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.j2eeresourceproperty.ignore", "false"), "ignore","J2EEResourceProperty");
  if len(atts) != 0:
    print "Modifying J2EEResourceProperty with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Util.popPathElement('J2EEResourceProperty');
