###
# Licensed Materials - Property of IBM* and/or HCL**
# (c) Copyright IBM Corporation 2014, 2015, 2017. All Rights Reserved.
# (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
#
# U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
# GSA ADP Schedule Contract with IBM Corp.
#
# * Trademark of International Business Machines
# ** Trademark of HCL Technologies Limited

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



__name_att__ = None;

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

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

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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.datasourceref.name", objid, "name","DataSource");

  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  name = roleProperties.getString('websphere.datasourceref.name');

  cmpPosition = parentid.find("#CMPConnectorFactory_");  
  idPosition = parentid.find("(cells/");
  ancestorPath = parentid[idPosition:cmpPosition];
  
  dataSourceRef = None;
  dataSources = Util.getid("/DataSource:/").splitlines();
  if len(dataSources) > 0:
    for dataSource in dataSources:
      if len(dataSource) > 0:
        sourcePosition = dataSource.find("#DataSource_");
        sourceIdPosition = dataSource.find("(cells/");
        ancestor = dataSource[sourceIdPosition:sourcePosition];
        #Only find in DataSources within the same scope
        if ancestorPath == ancestor:      
          sourceName = Util.getRequiredAttribute(dataSource, "name", "DataSource" );
          if (name == sourceName):
            dataSourceRef = dataSource;
            break;
  
  if dataSourceRef is None or len(dataSourceRef) < 1:
    raise Exception("Could not find DataSource named %(name)s" % { 'name':name} );

  properties = [];
  properties.append(['cmpDatasource', dataSourceRef]);
  Log.debug(properties);
  Log.debug(parentid);
  print "Creating DataSourceRef to %(id)s for cmpDatasource" % { 'id': dataSourceRef};
  objid = Util.modify(parentid, properties);
  Log.debug("Finished Creating DataSourceRef to %(id)s for cmpDataSource" % { 'id':dataSourceRef });
  Util.popPathElement('DataSourceRef');
