#- Licensed Materials - Property of IBM Corp.
#- IBM UrbanCode Deploy
#- (c) Copyright IBM Corporation 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 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 = parentid[parentid.find("/"):(parentid.find("|") + 1)];

  # 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
        if adminObject.find(parentScope) != -1:
          # 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;
