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('KeySetRef')

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

  roleProperties = JSONObject();
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keysetref.name", objid, "name","KeySet");
  
  scopeName = None;
  managementScope = Util.getOptionalAttribute(objid, 'managementScope', 'KeySet');
  if managementScope is not None and len(managementScope) > 0:
    scopeName = Util.getOptionalAttribute(managementScope, 'scopeName', 'ManagementScope');
    if scopeName is not None and len(scopeName) > 0:
      Util.addToJsonIfNotNone(roleProperties, "websphere.keysetref.scopename", scopeName);
  
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('KeySetRef');
  return result;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has('websphere.keysetref.name'):
    raise Exception("KeySetRef resource has no property named websphere.keysetref.name!");
  if not roleProperties.has('websphere.keysetref.scopename'):
    raise Exception("KeySetRef resource has no property named websphere.keysetref.scopename!");

  keySetName = roleProperties.getString('websphere.keysetref.name');
  keySetScopeName = roleProperties.getString('websphere.keysetref.scopename');

  keySetId = None;
  keySets = Util.getid("/KeySet:/").splitlines();
  if len(keySets) > 0:
    for keySet in keySets:
      if len(keySet) > 0:
        name = Util.getRequiredAttribute(keySet, "name", "KeySet" );
        scopeName = None;
        managementScope = Util.getOptionalAttribute(keySet, 'managementScope', 'KeySet');
        if managementScope is not None and len(managementScope) > 0:
          scopeName = Util.getOptionalAttribute(managementScope, 'scopeName', 'ManagementScope');

        if (keySetName == name and keySetScopeName == scopeName):
          keySetId = keySet;
          break;
  
  if keySetId is None or len(keySetId) < 1:
    raise Exception("Could not find keyset named %(name)s with management scopename of %(scopeName)s" % { 'name':keySetName, 'scopeName':keySetScopeName } );

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