#- Licensed Materials - Property of IBM Corp.
#- IBM UrbanCode Deploy
#- (c) Copyright IBM Corporation 2014, 2015. All Rights Reserved.
#-
#- U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
#- GSA ADP Schedule Contract with IBM Corp.

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, name = ""):
  Util.pushPathElement('ConnectionDefinitionRef')

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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.connectiondefinitionref.connectionimplclass", objid, "connectionImplClass","ConnectionDefinition");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.connectiondefinitionref.connectionfactoryimplclass", objid, "connectionFactoryImplClass","ConnectionDefinition");

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

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


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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  
  connectionimplclass = roleProperties.getString('websphere.connectiondefinitionref.connectionimplclass');
  factoryimplclass = roleProperties.getString('websphere.connectiondefinitionref.connectionfactoryimplclass');    

  parentType = "#%s_" % parentType;
  objPosition = parentid.find(parentType);
  idPosition = parentid.find("(cells/");
  ancestorPath = parentid[idPosition:objPosition];
  
  connDefinitionRef = None;
  connDefinitions = Util.getid('/ConnectionDefinition:/').splitlines();
  if len(connDefinitions) > 0:
    for connDefinition in connDefinitions:
      if len(connDefinition) > 0:
        connPosition = connDefinition.find("#ConnectionDefinition_");
        ancestoridPosition = connDefinition.find("(cells/");
        ancestor = connDefinition[ancestoridPosition:connPosition];
        #Only find in ConnectionDefinitions within the same scope
        if ancestorPath == ancestor:
          connectionimpl = Util.getOptionalAttribute(connDefinition, "connectionImplClass", "ConnectionDefinition" );
          factoryimpl = Util.getOptionalAttribute(connDefinition, "connectionFactoryImplClass", "ConnectionDefinition" );

          if (connectionimplclass == connectionimpl and factoryimplclass == factoryimpl):
            connDefinitionRef = connDefinition;
            break;
  
  if connDefinitionRef is None or len(connDefinitionRef) < 1:
    raise Exception("Could not find referenced Connection Definition with ImplClass %(conn)s and FactoryImplClass %(factory)s" % { 'conn':connectionimplclass, 'factory':factoryimplclass } );

  properties = [];
  properties.append([attr, connDefinitionRef]);
  Log.debug(properties);
  Log.debug(parentid);
  print "Creating ConnectionDefinitionRef to %(id)s for attribute %(attr)s" % { 'id':connDefinitionRef, 'attr':attr };
  objid = Util.modify(parentid, properties);
  Log.debug("Finished Creating ConnectionDefinitionRef to %(id)s for attribute %(attr)s" % { 'id':connDefinitionRef, 'attr':attr });
  Util.popPathElement('ConnectionDefinitionRef');

def find(ancestorid, jsonobject):

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  connectionimplclass = roleProperties.getString('websphere.connectiondefinitionref.connectionimplclass');
  factoryimplclass = roleProperties.getString('websphere.connectiondefinitionref.connectionfactoryimplclass');  

  connDefinitionRef = None;
  
  # get the scope of the parent
  parentScope = Util.getScope(ancestorid);

  # get all ConnectionDefinitions
  connectionDefinitions = Util.getid("/ConnectionDefinition:/").splitlines();
  if len(connectionDefinitions) > 0:
    for connectionDefinition in connectionDefinitions:
      if len(connectionDefinition) > 0:
        # see if this connectionDefinition id contains the same scope as the parent object
        connectionDefinitionScope = Util.getScope(connectionDefinition);
        if parentScope == connectionDefinitionScope:
          # now that we know the connectionDefinition is in the same scope as our parent object,
          # get the connectionDefinition's connectionImplClass and connectionFactoryImplClass attributes
          # and see if they match the values in our JSON object
          connectionimpl = Util.getOptionalAttribute(connectionDefinition, "connectionImplClass", "ConnectionDefinition" );
          factoryimpl = Util.getOptionalAttribute(connectionDefinition, "connectionFactoryImplClass", "ConnectionDefinition" );
          if (connectionimplclass == connectionimpl and factoryimplclass == factoryimpl):
            connDefinitionRef = connectionDefinition;
            break;

  return connDefinitionRef;
