from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from ManagementScopeRef import ManagementScopeRef
from KeySetRef import KeySetRef
from WSScheduleRef import WSScheduleRef
from WASConfLog import Log

__name_att__ = None;

def _export(objid, parentrespath, name = ""):
  Util.pushPathElement('KeySetGroup')


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keysetgroup.name", objid, "name","KeySetGroup");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keysetgroup.autogenerate", objid, "autoGenerate","KeySetGroup");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  managementScope = Util.getOptionalAttribute(objid, 'managementScope', 'KeySetGroup');
  if managementScope is not None and len(managementScope) > 0:
    returndict = Util.createTypeFolder(respath, "ManagementScopeRef", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, ManagementScopeRef._export(managementScope, currespath, "ManagementScope"));

  i = 0;
  keySets = Util.parseConfigIdListAttribute(objid, 'keySet', "KeySetGroup");
  for keySet in keySets:
    if len(keySet) > 0:
      returndict = Util.createTypeFolder(respath, "KeySetRef", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, KeySetRef._export(keySet, currespath, "KeySet%s" % i));
      i = i + 1;

  wsSchedule = Util.getOptionalAttribute(objid, 'wsSchedule', 'KeySetGroup');
  if wsSchedule is not None and len(wsSchedule) > 0:
    returndict = Util.createTypeFolder(respath, "WSScheduleRef", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, WSScheduleRef._export(wsSchedule, currespath, "WSSchedule"));

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.keysetgroup.name", None));
  Util.addIfNotNone(properties, "autoGenerate", roleProperties.optString("websphere.keysetgroup.autogenerate", None));
  print "Creating KeySetGroup with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("KeySetGroup", parentid, properties);

  if jsonobject.has('children'):
    for currjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = currjsonobject.getString('roleName');
      if currole == "WebSphereManagementScopeRef":
        ManagementScopeRef.create(objid, currjsonobject, "managementScope");
      elif currole == "WebSphereKeySetRef":
        KeySetRef.create(objid, currjsonobject, "keySet");
      elif currole == "WebSphereWSScheduleRef":
        WSScheduleRef.create(objid, currjsonobject, "wsSchedule");
  Util.popPathElement('KeySetGroup');

def update(objid,jsonobject):
  Util.pushPathElement('KeySetGroup')
  if not jsonobject.has("roleProperties"):
    raise Exception("KeySetGroup resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keysetgroup.name", None), "name","KeySetGroup");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.keysetgroup.autogenerate", None), "autoGenerate","KeySetGroup");
  if len(atts) != 0:
    print "Modifying KeySetGroup with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

    Util.modify(objid, atts);
  else:   
    print "KeySetGroup configuration up to date.";

  Util.unsetAttribute(objid, "managementScope", "KeySetGroup");
  Util.unsetAttribute(objid, "keySet", "KeySetGroup");
  Util.unsetAttribute(objid, "wsSchedule", "KeySetGroup");

  if jsonobject.has('children'):
    for currjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = currjsonobject.getString('roleName');
      if currole == "WebSphereManagementScopeRef":
        ManagementScopeRef.create(objid, currjsonobject, "managementScope");
      elif currole == "WebSphereKeySetRef":
        KeySetRef.create(objid, currjsonobject, "keySet");
      elif currole == "WebSphereWSScheduleRef":
        WSScheduleRef.create(objid, currjsonobject, "wsSchedule");
  Util.popPathElement('KeySetGroup');

def find(parentid, jsonobject, targetScopeName):
  if not jsonobject.has("roleProperties"):
    raise Exception("KeySetGroup resource has no role properties!");

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

  keySetGroupName = roleProperties.getString('websphere.keysetgroup.name');

  # find the KeySetGroup based on the KeySetGroup name and the KeySetGroup's ManagementScope's scopeName.
  # There can't be > 1 KeySetGroup with the same name in the same scope, so this should work
  keySetGroupId = None;
  keySetGroups = Util.getid("/KeySetGroup:/").splitlines();
  if len(keySetGroups) > 0:
    for keySetGroup in keySetGroups:
      if len(keySetGroup) > 0:
        name = Util.getRequiredAttribute(keySetGroup, "name", "KeySetGroup" );
        if (keySetGroupName == name ):
          # get the managementScope attribute of the KeySetGroup
          managementScope = Util.getRequiredAttribute(keySetGroup, "managementScope", "KeySetGroup" );
          # get the scopeName attribute of the managementScope
          scopeName = Util.getRequiredAttribute(managementScope, "scopeName", "ManagementScope" );
          if (targetScopeName == scopeName):
            keySetGroupId = keySetGroup;
            break;

  if keySetGroupId is None or len(keySetGroupId) < 1:
    Log.log("Could not find KeySetGroup named %(name)s with ManagementScope scopeName of %(ms)s. May need to create one." % { 'name':keySetGroupName, 'ms':targetScopeName } );

  return keySetGroupId;
