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

__name_att__ = "websphere.was40datasource.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.was40datasource.name", objid, "name","WAS40DataSource");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.was40datasource.category", objid, "category","WAS40DataSource");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.was40datasource.defaultpassword", objid, "defaultPassword","WAS40DataSource");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.was40datasource.defaultuser", objid, "defaultUser","WAS40DataSource");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.was40datasource.providertype", objid, "providerType","WAS40DataSource");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.was40datasource.jndiname", objid, "jndiName","WAS40DataSource");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.was40datasource.databasename", objid, "databaseName","WAS40DataSource");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.was40datasource.description", objid, "description","WAS40DataSource");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"WAS40DataSource");
  connPool = Util.getOptionalAttribute(objid, 'connectionPool', 'WAS40DataSource');
  if connPool is not None and len(connPool) > 0:
    returndict = Util.createTypeFolder(respath, "WAS40ConnectionPool", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, WAS40ConnectionPool._export(connPool, currespath, 'WAS40ConnectionPool'));

  respropset = Util.getOptionalAttribute(objid, 'propertySet', 'WAS40DataSource');
  if respropset is not None and len(respropset) > 0:
    returndict = Util.createTypeFolder(respath, "J2EEResourcePropertySet", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, J2EEResourcePropertySet._export(respropset, currespath, 'J2EEResourcePropertySet'));

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



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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.was40datasource.name", None));
  Util.addIfNotNone(properties, "category", roleProperties.optString("websphere.was40datasource.category", None));
  Util.addIfNotNone(properties, "defaultPassword", roleProperties.optString("websphere.was40datasource.defaultpassword", None));
  Util.addIfNotNone(properties, "defaultUser", roleProperties.optString("websphere.was40datasource.defaultuser", None));
  Util.addIfNotNone(properties, "providerType", roleProperties.optString("websphere.was40datasource.providertype", None));
  Util.addIfNotNone(properties, "jndiName", roleProperties.optString("websphere.was40datasource.jndiname", None));
  Util.addIfNotNone(properties, "databaseName", roleProperties.optString("websphere.was40datasource.databasename", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.was40datasource.description", None));
  print "Creating WAS40DataSource with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("WAS40DataSource", parentid, properties);

  Property.removeProperties(objid, 'properties',"WAS40DataSource");

  connPool = Util.getOptionalAttribute(objid, 'connectionPool', 'WAS40DataSource');
  if connPool is not None and len(connPool) > 0:
    Util.remove(connPool);

  propset = Util.getOptionalAttribute(objid, 'propertySet', 'WAS40DataSource');
  if propset is not None and len(propset) > 0:
    Util.remove(propset);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if currole == "WebSphereWAS40ConnectionPool":
        WAS40ConnectionPool.create(objid, curjsonobject);
      elif currole == "WebSphereJ2EEResourcePropertySet":
        J2EEResourcePropertySet.create(objid, curjsonobject);
  Util.popPathElement('WAS40DataSource');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.was40datasource.name", None), "name","WAS40DataSource");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.was40datasource.category", None), "category","WAS40DataSource");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.was40datasource.defaultpassword", None), "defaultPassword","WAS40DataSource");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.was40datasource.defaultuser", None), "defaultUser","WAS40DataSource");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.was40datasource.providertype", None), "providerType","WAS40DataSource");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.was40datasource.jndiname", None), "jndiName","WAS40DataSource");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.was40datasource.databasename", None), "databaseName","WAS40DataSource");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.was40datasource.description", None), "description","WAS40DataSource");
  if len(atts) != 0:
    print "Modifying WAS40DataSource with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Property.removeProperties(objid, 'properties',"WAS40DataSource");

  connPool = Util.getOptionalAttribute(objid, 'connectionPool', 'WAS40DataSource');
  if connPool is not None and len(connPool) > 0:
    Util.remove(connPool);

  propset = Util.getOptionalAttribute(objid, 'propertySet', 'WAS40DataSource');
  if propset is not None and len(propset) > 0:
    Util.remove(propset);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if currole == "WebSphereWAS40ConnectionPool":
        WAS40ConnectionPool.create(objid, curjsonobject);
      elif currole == "WebSphereJ2EEResourcePropertySet":
        J2EEResourcePropertySet.create(objid, curjsonobject);

  Util.popPathElement('WAS40DataSource');

def getWAS40DataSources(objid):
  was40DataSources = Util.getAssociatedObjects(objid, "WAS40DataSource");
  return was40DataSources;

