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

__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 doImportPartial(containmentpath, roleName, jsonobject):
  doImport(containmentpath, roleName, jsonobject);

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:
    if Util.__removePartialConfig__ == "false":
      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.";

  #If you not adding or removing individual VariableSubstitutionEntries, then clear out existing
  #entries so we can refresh the entire list.
  if Util.__applyPartialConfig__ == "false" and Util.__removePartialConfig__ == "false":
    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);
      existingVSE = findVariableSubstitutionEntry(objid, parts[0]);
      if existingVSE == None or len(existingVSE) == 0:
        if Util.__removePartialConfig__ == "false":
          Util.create("VariableSubstitutionEntry", objid, [['symbolicName', parts[0]],['description',parts[1]],['value',parts[2]]]);
      else:
        if Util.__removePartialConfig__ == "true":
          Util.removePartialApply(existingVSE);
          existingVSE = None;
        else:
          Util.modify(existingVSE, [['symbolicName', parts[0]],['description',parts[1]],['value',parts[2]]]);

  Util.popPathElement('VariableMap');

def findVariableSubstitutionEntry(objid, name):
  entries = Util.parseConfigIdListAttribute(objid,'entries',"VariableMap");
  for entry in entries:
    symName = Util.getRequiredAttribute(entry, 'symbolicName', 'VariableSubstitutionEntry');
    Log.debug("Comparing VariableSubstitutionEntry named %(symName)s to %(name)s" % { 'symName': symName, 'name': name });
    if symName == name:
      return entry;
