#- 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('SecurityRoleExtRef')

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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securityroleextref.rolename", objid, "roleName","SecurityRoleExt");

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

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


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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  
  roleName = roleProperties.getString('websphere.securityroleextref.rolename');

  parentType = "#%s_" % parentType;
  objPosition = parentid.find(parentType);
  idPosition = parentid.find("(cells/");
  ancestorPath = parentid[idPosition:objPosition];
  
  securityRoleExtRef = None;
  securityRoleExts = Util.getid('/SecurityRoleExt:/').splitlines();
  if len(securityRoleExts) > 0:
    for securityRoleExt in securityRoleExts:
      if len(securityRoleExt) > 0:
        extPosition = securityRoleExt.find("#SecurityRoleExt_");
        ancestor = securityRoleExt[0:extPosition];
        #Only find SecurityRoleExt objects within the same scope
        if ancestorPath == ancestor:
          foundRoleName = Util.getOptionalAttribute(securityRoleExt, "roleName", "SecurityRoleExt" );

          if (roleName == foundRoleName):
            securityRoleExtRef = securityRoleExt;
            break;
  
  if securityRoleExtRef is None or len(securityRoleExtRef) < 1:
    raise Exception("Could not find referenced SecurityRoleExt with rolename %(name)s" % { 'name':roleName } );

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