###
# Licensed Materials - Property of IBM* and/or HCL**
# (c) Copyright IBM Corporation 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 WASConfLog import Log;
from utilities import Util

__name_att__ = None;


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

  if parentrespath == "/":
    parentrespath = "";
  respath = "%(parentrespath)s/%(name)s" % { 'parentrespath':parentrespath, 'name':resname }
  if not respath.startswith("/"):
    respath = "/" + respath;

  exportedObject = JSONObject();
  exportedObject.put("name", resname);
  exportedObject.put("path", respath);
  exportedObject.put("teamMappings", JSONArray());
  exportedObject.put("inheritTeam", "true");
  exportedObject.put("description", "Discovered WebSphereAdminObjectRef");
  exportedObject.put("roleName", "WebSphereAdminObjectRef");

  roleProperties = JSONObject();
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.adminobject.adminobjectclass", objid, "adminObjectClass", "AdminObject");

  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('AdminObjectRef');
  return result;

def doImport(parentid, jsonobject):
  referencedAdminObject = getReferencedAdminObject(parentid, jsonobject);
  # no need to push any path elements as we are modifying the parent, which should have already pushed its path element since they must directly call into the import method
  Util.modify(parentid, [['adminObject', referencedAdminObject]]);

def getReferencedAdminObject(parentid, jsonobject):

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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has('websphere.adminobject.adminobjectclass'):
    raise Exception("AdminObjectRef resource has no property named websphere.adminobject.adminobjectclass!");

  targetAdminObjectClass = roleProperties.getString('websphere.adminobject.adminobjectclass');
  referencedAdminObject = None;

  # to find the scope of the AdminObject we are looking for,
  # take the parentid and get everything between the first / and |
  # example parentid = test(cells/CloudBurstCell_1/nodes/CloudBurstNode_1|resources.xml#AdminObjectTemplateProps_1431703712950)
  # this would make parentScope below = /CloudBurstCell_1/nodes/CloudBurstNode_1
  parentScope = Util.getScope(parentid);

  # get all AdminObjects
  adminObjects = Util.getid("/AdminObject:/").splitlines();
  if len(adminObjects) > 0:
    for adminObject in adminObjects:
      if len(adminObject) > 0:
        # see if this AdminObject id contains the same scope as the parentid
        adminObjectScope = Util.getScope(adminObject);
        if adminObjectScope == parentScope:
          # get the adminObjectClass attribute of this AdminObject
          adminObjectClass = Util.getOptionalAttribute(adminObject, "adminObjectClass", "AdminObject");
          if adminObjectClass != None or len(adminObjectClass) > 0:
            if adminObjectClass == targetAdminObjectClass:
              referencedAdminObject = adminObject;
              break;

  if referencedAdminObject == None or len(referencedAdminObject) == 0:
      raise Exception("Could not find AdminObject with adminObjectClass " + targetAdminObjectClass + " in scope " + parentScope + ".");
  return referencedAdminObject;
