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

__name_att__ = "websphere.jdbcprovider.name"

def export(objid, parentcontainmentpath, parentrespath):

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

  containmentpath = "%(parentconpath)sJDBCProvider:%(name)s/" % {'parentconpath':parentcontainmentpath, 'name':name }
  if not containmentpath.startswith("/"):
    containmentpath = "/" + containmentpath;

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

def _export(objid, parentrespath, containmentpath):
  Util.pushPathElement('JDBCProvider')

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

  #Since WebSphere allows duplicates names for JDBCProviders,
  #check to see if there are multiple objids that use this same containment path.
  #If there are multiple entries, then create a unique resource name to use in
  #the UCD resource tree because the resource tree does not allow duplicate names.
  checkids = Util.getid(containmentpath).splitlines();
  if len(checkids) > 1:
    Log.log("Duplicate JDBCProvider names found for %s.  Adding unique qualifier" % containmentpath);
    if ((objid.rfind("#") > 0)):
      #Remove double quotes if they exist
      objidNoQuotes = objid.replace('\"','');
      uniqueId = objidNoQuotes[objidNoQuotes.rfind("#") : len(objidNoQuotes)-1];
      name = name + " - " + uniqueId;

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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jdbcprovider.xa", objid, "xa","JDBCProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jdbcprovider.name", objid, "name","JDBCProvider");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.jdbcprovider.classpath", objid, "classpath","JDBCProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jdbcprovider.providertype", objid, "providerType","JDBCProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jdbcprovider.implementationclassname", objid, "implementationClassName","JDBCProvider");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.jdbcprovider.nativepath", objid, "nativepath","JDBCProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jdbcprovider.description", objid, "description","JDBCProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.jdbcprovider.isolatedclassloader", objid, "isolatedClassLoader","JDBCProvider");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  dataSources = DataSource.getDataSources(objid);
  if dataSources != None and len(dataSources) > 0:
    for dataSource in dataSources:
      if len(dataSource) > 0:
        returndict = Util.createTypeFolder(respath, "DataSource", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        Util.addAllFromExport(extraObjects, DataSource._export(dataSource, currespath));

  was40dataSources = WAS40DataSource.getWAS40DataSources(objid);
  if was40dataSources != None and len(was40dataSources) > 0:
    for was40dataSource in was40dataSources:
      if len(was40dataSource) > 0:
        returndict = Util.createTypeFolder(respath, "WAS40DataSource", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        Util.addAllFromExport(extraObjects, WAS40DataSource._export(was40dataSource, currespath));

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



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

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

  #Retrieve unique identifier added to the end of the JDBC provider name if it exists
  uniqueid = None;
  resourceName = jsonobject.get("name");
  if ((resourceName.rfind("#") > 0)):
    #Remove double quotes if they exist
    resourceNameNoQuotes = resourceName.replace('\"','');
    uniqueid = resourceNameNoQuotes[resourceNameNoQuotes.rfind("#") : len(resourceNameNoQuotes)];

  objid = None;
  #If JDBCProvider name does not contain a unique ending, then we can only proceeed
  #if there is only 1 entry in the containment path matching this name.
  if uniqueid is None:
    checkids = Util.getid(containmentpath).splitlines();
    if len(checkids) > 1:
      raise Exception("Unable to uniquely identify JDBCProvider to import. Make JDBCProvider name unique");
    else:
      objid = Util.getid(containmentpath);

  #If we haven't found proper object yet and we didn't raise an exception, then we must have a list.
  #See if we can find it using unique id.
  if objid is None:
    Log.log("Import JDBCProvider uniqueid: %s" % uniqueid);
    #If multiple objects have the same containment path, then we need to find the right one.
    objids = Util.getid(containmentpath).splitlines();
    for obj in objids:
      if len(obj) > 0:
        Log.log("Import JDBCProvider checking objectid for match: %s" % obj);
        if obj.find(uniqueid) != -1:
          Log.log("Import JDBCProvider found matching objectid: %s" % obj);
          objid = obj;
          break;

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "xa", roleProperties.optString("websphere.jdbcprovider.xa", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.jdbcprovider.name", None));
  Util.addPathProperty(properties, "classpath", roleProperties.optString("websphere.jdbcprovider.classpath", None));
  Util.addIfNotNone(properties, "providerType", roleProperties.optString("websphere.jdbcprovider.providertype", None));
  Util.addIfNotNone(properties, "implementationClassName", roleProperties.optString("websphere.jdbcprovider.implementationclassname", None));
  Util.addPathProperty(properties, "nativepath", roleProperties.optString("websphere.jdbcprovider.nativepath", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.jdbcprovider.description", None));
  Util.addIfNotNone(properties, "isolatedClassLoader", roleProperties.optString("websphere.jdbcprovider.isolatedclassloader", None));
  print "Creating JDBCProvider with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("JDBCProvider", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereDataSource":
        DataSource.create(objid, curjsonobject);
      elif currole == "WebSphereWAS40DataSource":
        WAS40DataSource.create(objid, curjsonobject);

  Util.popPathElement('JDBCProvider');
  return objid;

def update(objid,jsonobject):
  Util.pushPathElement('JDBCProvider')

  if not jsonobject.has("roleProperties"):
    raise Exception("JDBCProvider resource has no role properties!");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jdbcprovider.xa", None), "xa","JDBCProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jdbcprovider.name", None), "name","JDBCProvider");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.jdbcprovider.classpath", None), "classpath","JDBCProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jdbcprovider.providertype", None), "providerType","JDBCProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jdbcprovider.implementationclassname", None), "implementationClassName","JDBCProvider");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.jdbcprovider.nativepath", None), "nativepath","JDBCProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jdbcprovider.description", None), "description","JDBCProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.jdbcprovider.isolatedclassloader", None), "isolatedClassLoader","JDBCProvider");
  if len(atts) != 0:
    print "Modifying JDBCProvider with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  dataSources = DataSource.getDataSources(objid);
  if dataSources != None and len(dataSources) > 0:
    for dataSource in dataSources:
      if len(dataSource) > 0:
        Util.remove(dataSource);
  
  was40DataSources = WAS40DataSource.getWAS40DataSources(objid);
  if was40DataSources != None and len(was40DataSources) > 0:
    for was40DataSource in was40DataSources:
      if len(was40DataSource) > 0:
        Util.remove(was40DataSource);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereDataSource":
        DataSource.create(objid, curjsonobject);
      elif currole == "WebSphereWAS40DataSource":
        WAS40DataSource.create(objid, curjsonobject);

  Util.popPathElement('JDBCProvider');
