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

__name_att__ = None;

def export(objid, parentcontainmentpath, parentrespath):

  name = "VariableMap";

  containmentpath = "%(parentconpath)sVariableMap:/" % {'parentconpath':parentcontainmentpath}
  if not containmentpath.startswith("/"):
    containmentpath = "/" + containmentpath;

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

def _export(objid, parentrespath, name = "VariableMap"):
  Util.pushPathElement('VariableMap')


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

  roleProperties = JSONObject();
  entryString = "";
  entries = Util.parseConfigIdListAttribute(objid, 'entries',"VariableMap");
  first = 0;
  for entry in entries:
    if first == 0:
      first = 1;
    else:
      entryString = "%s\n" % entryString;
    symName = Util.getRequiredAttribute(entry, 'symbolicName', 'VariableSubstitutionEntry');
    desc = Util.getOptionalAttribute(entry, 'description', 'VariableSubstitutionEntry');
    value = Util.getOptionalAttribute(entry, 'value', 'VariableSubstitutionEntry');
    entryString = "%(cur)s%(name)s->%(desc)s->%(value)s" % { 'cur': entryString, 'name': symName, 'desc':desc, 'value': value };
  Util.addToJsonIfNotNone(roleProperties, "websphere.variablemap.entries", entryString);

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


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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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


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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  print "Creating VariableMap with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("VariableMap", parentid, properties);

  if roleProperties.has("websphere.variablemap.entries"):
    entries = roleProperties.getString("websphere.variablemap.entries").splitlines();
    for entry in entries:
      parts = entry.split("->", 2);
      Util.create("VariableSubstitutionEntry", objid, [['symbolicName', parts[0]],['description',parts[1]],['value',parts[2]]]);
  Util.popPathElement('VariableMap');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  if len(atts) != 0:
    print "Modifying VariableMap with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  entries = Util.parseConfigIdListAttribute(objid, 'entries',"VariableMap");
  for entry in entries:
    Util.remove(entry);

  if roleProperties.has("websphere.variablemap.entries"):
    entries = roleProperties.getString("websphere.variablemap.entries").splitlines();
    for entry in entries:
      parts = entry.split("->", 2);
      Util.create("VariableSubstitutionEntry", objid, [['symbolicName', parts[0]],['description',parts[1]],['value',parts[2]]]);
  Util.popPathElement('VariableMap');
