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

__name_att__ = "websphere.property.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.property.validationexpression", objid, "validationExpression","Property");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.property.name", objid, "name","Property");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.property.description", objid, "description","Property");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.property.value", objid, "value","Property");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.property.required", objid, "required","Property");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('Property');
  return result;


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

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

  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 Property on.");
      objid = create(parentid, jsonobject);
  else:
    if Util.__removePartialConfig__ == "true":
      Util.removePartialApply(objid);
      objid = None;
    else:
      update(objid,jsonobject);
  return objid;

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "validationExpression", roleProperties.optString("websphere.property.validationexpression", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.property.name", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.property.description", None));
  Util.addIfNotNone(properties, "value", roleProperties.optString("websphere.property.value", None));
  Util.addIfNotNone(properties, "required", roleProperties.optString("websphere.property.required", None));
  print "Creating Property with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("Property", parentid, properties, attName);
  Util.popPathElement('Property');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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


def removeProperties(objid, attributeName, parentType):
  props = Util.parseConfigIdListAttribute(objid, attributeName, parentType);
  for prop in props:
    Util.remove(prop);

def exportProperties(objid, respath, extraObjects, typeFolders, attributeName, parentType, folderName = None, hardcoded = 0):
  props = Util.parseConfigIdListAttribute(objid, attributeName, parentType);
  for prop in props:
    if prop.find("#TypedProperty_") > 0:
      if folderName is not None and len(folderName) > 0:
        returndict = Util.createTypeFolder(respath, folderName, typeFolders, hardcoded);
      else:
        returndict = Util.createTypeFolder(respath, "TypedProperty", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, TypedProperty._export(prop, currespath));
    elif prop.find("#DescriptiveProperty_") > 0:
      if folderName is not None and len(folderName) > 0:
        returndict = Util.createTypeFolder(respath, folderName, typeFolders, hardcoded);
      else:
        returndict = Util.createTypeFolder(respath, "DescriptiveProperty", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, DescriptiveProperty._export(prop, currespath));
    elif prop.find("#DiscoverableDescriptiveProperty_") > 0:
      if folderName is not None and len(folderName) > 0:
        returndict = Util.createTypeFolder(respath, folderName, typeFolders, hardcoded);
      else:
        returndict = Util.createTypeFolder(respath, "DiscoverableDescriptiveProperty", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, DiscoverableDescriptiveProperty._export(prop, currespath));
    elif prop.find("#Property_") > 0:
      if folderName is not None and len(folderName) > 0:
        returndict = Util.createTypeFolder(respath, folderName, typeFolders, hardcoded);
      else:
        returndict = Util.createTypeFolder(respath, "Property", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, _export(prop, currespath));
  return extraObjects;

def createObjIfRole(objid, curjsonobject, currole, attName = None):
  if currole == "WebSphereDiscoverableDescriptiveProperty":
    DiscoverableDescriptiveProperty.create(objid, curjsonobject, attName);
    return 1;
  elif currole == "WebSphereTypedProperty":
    TypedProperty.create(objid, curjsonobject, attName);
    return 1;
  elif currole == "WebSphereDescriptiveProperty":
    DescriptiveProperty.create(objid, curjsonobject, attName);
    return 1;
  elif currole == "WebSphereProperty":
    create(objid, curjsonobject, attName);
    return 1;
  return 0;

def updateProperties(objid, jsonObjectList, attName, curType, cleanUnupdated = 0):
  curPropertyObjList = Util.parseConfigIdListAttribute(objid, attName, curType);
  curPropertyMap = {};# we'll assume there aren't already duplicate named properties on this object.
  for x in curPropertyObjList:
    name = Util.getRequiredAttribute(x, 'name', 'Property');
    curPropertyMap[name] = x;

  for x in jsonObjectList:
    roleName = x.getString('roleName')
    roleType = Util.roleNameToType(roleName).lower();
    roleProperties = x.getJSONObject('roleProperties');
    name = roleProperties.getString("websphere.%s.name" % roleType);
    if curPropertyMap.has_key(name):
      Util.remove(curPropertyMap[name]);
      del curPropertyMap[name];
    createObjIfRole(objid, x, roleName, attName);

  if cleanUnupdated:
    for x in curPropertyMap.values():
      Util.remove(x);
  

def isPropertyRole(currole):
  if currole == "WebSphereDiscoverableDescriptiveProperty":
    return 1;
  elif currole == "WebSphereTypedProperty":
    return 1;
  elif currole == "WebSphereDescriptiveProperty":
    return 1;
  elif currole == "WebSphereProperty":
    return 1;
  return 0;
