from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from Property import Property
from RepositoryService import RepositoryService
from ExtensionMBeanProvider import ExtensionMBeanProvider
from PluginConfigService import PluginConfigService
from JMXConnector import JMXConnector
from JMXConnectorRef import JMXConnectorRef
from WASConfLog import Log;
from utilities import Util
from com.ibm.ws.scripting import ScriptingException

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.adminservice.standalone", objid, "standalone","AdminService");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.adminservice.enable", objid, "enable","AdminService");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"AdminService");

  connectorId2ResourceName = JMXConnector.exportJMXConnectors(objid, respath, extraObjects, typeFolders, 'connectors',"AdminService");

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

  pluginConfigService = Util.getOptionalAttribute(objid, 'pluginConfigService', 'AdminService');
  if pluginConfigService is not None and len(pluginConfigService) > 0:
    returndict = Util.createTypeFolder(respath, "PluginConfigService", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, PluginConfigService._export(pluginConfigService, currespath, 'Plugin Config Service'));

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

  preferredConnector = Util.getOptionalAttribute(objid, 'preferredConnector', 'AdminService');

  # The localAdminProtocol and remoteAdminProtocol attributes are not always present for a AdminService configuration object so we need to handle the exception that
  # occurs when they are not present.  We think the issue may be introduced during migration from WebSphere 6 to WebSphere 7.
  localAdminProtocol = None;
  remoteAdminProtocol = None;
  try:
    localAdminProtocol = Util.getOptionalAttribute(objid, 'localAdminProtocol', 'AdminService');
  except ScriptingException, msg:
    Log.debug("Util.getOptionalAttribute failure: %s" % msg);

  try:
    remoteAdminProtocol = Util.getOptionalAttribute(objid, 'remoteAdminProtocol', 'AdminService');
  except ScriptingException, msg:
    Log.debug("Util.getOptionalAttribute failure: %s" % msg);
  
  if preferredConnector is not None and len(preferredConnector) > 0:
    returndict = Util.createTypeFolder(respath, 'Preferred Connectors', typeFolders, 1);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, JMXConnectorRef._export(currespath, connectorId2ResourceName[preferredConnector], 'Preferred Connector'));

  if localAdminProtocol is not None and len(localAdminProtocol) > 0:
    returndict = Util.createTypeFolder(respath, 'Preferred Connectors', typeFolders, 1);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, JMXConnectorRef._export(currespath, connectorId2ResourceName[localAdminProtocol], 'Local Admin Connector'));

  if remoteAdminProtocol is not None and len(remoteAdminProtocol) > 0:
    returndict = Util.createTypeFolder(respath, 'Preferred Connectors', typeFolders, 1);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, JMXConnectorRef._export(currespath, connectorId2ResourceName[remoteAdminProtocol], 'Remote Admin Connector'));

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "standalone", roleProperties.optString("websphere.adminservice.standalone", None));
  Util.addIfNotNone(properties, "enable", roleProperties.optString("websphere.adminservice.enable", None));
  print "Creating AdminService with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("AdminService", parentid, properties);
  JMXConnector.removeJMXConnectors(objid, 'connectors', "AdminService");

  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    connectorName2IdDict = JMXConnector.updateJMXConnectors(objid, 'connectors', children, "AdminService");
    for curjsonobject in children:
      currole = curjsonobject.getString('roleName');
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if (propertyObject == 0):
        if currole == "WebSphereRepositoryService":
          RepositoryService.create(objid, curjsonobject);
        elif currole == "WebSphereExtensionMBeanProvider":
          ExtensionMBeanProvider.create(objid, curjsonobject);
        elif currole == "WebSpherePluginConfigService":
          PluginConfigService.create(objid, curjsonobject, threadPoolLookupPath);
    #ensure all jmxconnectors are actually created then create the references
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      curname = curjsonobject.getString('name');
      if currole == "WebSphereJMXConnectorRef":
        attname = ''
        if curname == 'Local Admin Connector':
          attName = 'localAdminProtocol';
        elif curname == 'Remote Admin Connector':
          attName = 'remoteAdminProtocol';
        elif curname == 'Preferred Connector':
          attName = 'preferredConnector';
        JMXConnectorRef.create(objid, curjsonobject, attName, connectorName2IdDict);
  Util.popPathElement('AdminService');
    



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  Property.removeProperties(objid, 'properties', "AdminService");


  configRepository = Util.getOptionalAttribute(objid, 'configRepository', 'AdminService');
  if configRepository is not None and len(configRepository) > 0:
    Util.remove(configRepository);

  pluginConfigService = Util.getOptionalAttribute(objid, 'pluginConfigService', 'AdminService');
  if pluginConfigService is not None and len(pluginConfigService) > 0:
    Util.remove(pluginConfigService);

  extensionMBeanProviders = Util.parseConfigIdListAttribute(objid, 'extensionMBeanProviders',"AdminService");
  for extensionMBeanProvider in extensionMBeanProviders:
    if len(extensionMBeanProvider) > 0:
      Util.remove(extensionMBeanProvider);

  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    connectorName2IdDict = JMXConnector.updateJMXConnectors(objid, 'connectors', children, "AdminService");
    for curjsonobject in children:
      currole = curjsonobject.getString('roleName');
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if (propertyObject == 0):
        if currole == "WebSphereRepositoryService":
          RepositoryService.create(objid, curjsonobject);
        elif currole == "WebSphereExtensionMBeanProvider":
          ExtensionMBeanProvider.create(objid, curjsonobject);
        elif currole == "WebSpherePluginConfigService":
          PluginConfigService.create(objid, curjsonobject, threadPoolLookupPath);
    #ensure all jmxconnectors are actually created then create the references
    for curjsonobject in children:
      currole = curjsonobject.getString('roleName');
      curname = curjsonobject.getString('name');
      if currole == "WebSphereJMXConnectorRef":
        attname = ''
        if curname == 'Local Admin Connector':
          attName = 'localAdminProtocol';
        elif curname == 'Remote Admin Connector':
          attName = 'remoteAdminProtocol';
        elif curname == 'Preferred Connector':
          attName = 'preferredConnector';
        JMXConnectorRef.create(objid, curjsonobject, attName, connectorName2IdDict);
  Util.popPathElement('AdminService');
