from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from Service import Service
from NodeAgent import NodeAgent
from NameServer import NameServer
from SecurityServer import SecurityServer
from EJBContainer import EJBContainer
from JobManager import JobManager
from JMSServer import JMSServer
from Agent import Agent
from ServerComponent import ServerComponent
from WebContainer import WebContainer
from ForeignServer import ForeignServer
from PortletContainer import PortletContainer
from SystemMessageServer import SystemMessageServer
from ExternallyManagedHTTPServer import ExternallyManagedHTTPServer
from WorkloadManagementServer import WorkloadManagementServer
from ExternalFileService import ExternalFileService
from ApplicationServer import ApplicationServer
from ApplicationContainer import ApplicationContainer
from WebServer import WebServer
from SIPContainer import SIPContainer
from CellManager import CellManager
from Proxy import Proxy
from OnDemandRouter import OnDemandRouter
from ProxyServer import ProxyServer
from Property import Property
from utilities import Util
from StateManageable import StateManageable

__name_att__ = None;

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


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

  roleProperties = JSONObject();

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

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"Component");
  extraObjects = exportComponents(objid, respath, extraObjects);
  extraObjects = Service.exportServices(objid, respath, extraObjects, typeFolders, 'services',"Component");

  stateManagement = Util.getRequiredAttribute(objid, 'stateManagement',"Component");
  if stateManagement is not None and len(stateManagement) > 0:
    returndict = Util.createTypeFolder(respath, "StateManageable", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, StateManageable._export(stateManagement, currespath, "StateManageable"));    
  
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('Component');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  removeComponents(objid);
  Property.removeProperties(objid, 'properties',"Component");
  Service.removeServices(objid, 'services', "Component");

  stateManagement = Util.getRequiredAttribute(objid, 'stateManagement',"Component");
  if stateManagement is not None and len(stateManagement) > 0:
    Util.remove(stateManagement);      
  
  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    for curjsonobject in children[:]:
      currole = curjsonobject.getString("roleName");
      serviceObject = Service.createObjIfRole(objid, curjsonobject, currole, threadPoolLookupPath);
      if serviceObject == 1:
        children.remove(curjsonobject);

    for curjsonobject in children[:]:
      currole = curjsonobject.getString("roleName");
      componentObject = createObjIfRole(objid, curjsonobject, currole, threadPoolLookupPath);
      if (componentObject == 0):
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
        if propertyObject == 0:    
          if currole == "WebSphereStateManageable":
            StateManageable.create(objid, curjsonobject);        
  Util.popPathElement('Component');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  removeComponents(objid);
  Property.removeProperties(objid, 'properties',"Component");
  Service.removeServices(objid, 'services', "Component");
  
  stateManagement = Util.getRequiredAttribute(objid, 'stateManagement',"Component");
  if stateManagement is not None and len(stateManagement) > 0:
    Util.remove(stateManagement);     

  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    for curjsonobject in children[:]:
      currole = curjsonobject.getString("roleName");
      serviceObject = Service.createObjIfRole(objid, curjsonobject, currole, threadPoolLookupPath);
      if serviceObject == 1:
        children.remove(curjsonobject);

    for curjsonobject in children[:]:
      currole = curjsonobject.getString("roleName");
      componentObject = createObjIfRole(objid, curjsonobject, currole, threadPoolLookupPath);
      if (componentObject == 0):
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
        if propertyObject == 0:    
          if currole == "WebSphereStateManageable":
            StateManageable.create(objid, curjsonobject);        
  Util.popPathElement('Component');

def removeComponents(objid, attributeName, parentType):
  components = Util.parseConfigIdListAttribute(objid, attributeName, parentType);
  if components is not None and len(components) > 0:
    for componentid in components:
      if len(componentid) > 0:
        Util.remove(componentid);

def exportComponents(objid, respath, extraObjects, typeFolders, attributeName, parentType):
  counterNodeAgent = 0;
  counterSecurityServer = 0;
  counterEJBContainer = 0;
  counterJobManager = 0;
  counterJMSServer = 0;
  counterAgent = 0;
  counterServerComponent = 0;
  counterWebContainer = 0;
  counterForeignServer = 0;
  counterPortletContainer = 0;
  counterSystemMessageServer = 0;
  counterExternallyManagedHTTPServer = 0;
  counterWorkloadManagementServer = 0;
  counterExternalFileService = 0;
  counterApplicationServer = 0;
  counterApplicationContainer = 0;
  counterWebServer = 0;
  counterNameServer = 0;
  counterSIPContainer = 0;
  counterCellManager = 0;
  counterProxy = 0;
  counterOnDemandRouter = 0;
  counterProxyServer = 0;

  components = Util.parseConfigIdListAttribute(objid, attributeName, parentType);
  if components is not None and len(components) > 0:
    for componentid in components:
      if len(componentid) > 0:
        pass;
        if componentid.find("#NodeAgent_") != -1:
          returndict = Util.createTypeFolder(respath, "NodeAgent", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, NodeAgent._export(componentid, currespath, 'NodeAgent%s' % counterNodeAgent));
          counterNodeAgent = counterNodeAgent + 1;
        elif componentid.find("#NameServer_") != -1:
          returndict = Util.createTypeFolder(respath, "NameServer", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, NameServer._export(componentid, currespath, 'NameServer%s' % counterNameServer));
          counterNameServer = counterNameServer + 1;
        elif componentid.find("#SecurityServer_") != -1:
          returndict = Util.createTypeFolder(respath, "SecurityServer", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, SecurityServer._export(componentid, currespath, 'SecurityServer%s' % counterSecurityServer));
          counterSecurityServer = counterSecurityServer + 1;
        elif componentid.find("#EJBContainer_") != -1:
          returndict = Util.createTypeFolder(respath, "EJBContainer", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, EJBContainer._export(componentid, currespath, 'EJBContainer%s' % counterEJBContainer));
          counterEJBContainer = counterEJBContainer + 1;
        elif componentid.find("#JobManager_") != -1:
          returndict = Util.createTypeFolder(respath, "JobManager", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, JobManager._export(componentid, currespath, 'JobManager%s' % counterJobManager));
          counterJobManager = counterJobManager + 1;
        elif componentid.find("#JMSServer_") != -1:
          returndict = Util.createTypeFolder(respath, "JMSServer", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, JMSServer._export(componentid, currespath, 'JMSServer%s' % counterJMSServer));
          counterJMSServer = counterJMSServer + 1;
        elif componentid.find("#Agent_") != -1:
          returndict = Util.createTypeFolder(respath, "Agent", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, Agent._export(componentid, currespath, 'Agent%s' % counterAgent));
          counterAgent = counterAgent + 1;
        elif componentid.find("#ServerComponent_") != -1:
          returndict = Util.createTypeFolder(respath, "ServerComponent", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, ServerComponent._export(componentid, currespath, 'ServerComponent%s' % counterServerComponent));
          counterServerComponent = counterServerComponent + 1;
        elif componentid.find("#WebContainer_") != -1:
          returndict = Util.createTypeFolder(respath, "WebContainer", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, WebContainer._export(componentid, currespath, 'WebContainer%s' % counterWebContainer));
          counterWebContainer = counterWebContainer + 1;
        elif componentid.find("#ForeignServer_") != -1:
          returndict = Util.createTypeFolder(respath, "ForeignServer", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, ForeignServer._export(componentid, currespath, 'ForeignServer%s' % counterForeignServer));
          counterForeignServer = counterForeignServer + 1;
        elif componentid.find("#PortletContainer_") != -1:
          returndict = Util.createTypeFolder(respath, "PortletContainer", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, PortletContainer._export(componentid, currespath, 'PortletContainer%s' % counterPortletContainer));
          counterPortletContainer = counterPortletContainer + 1;
        elif componentid.find("#SystemMessageServer_") != -1:
          returndict = Util.createTypeFolder(respath, "SystemMessageServer", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, SystemMessageServer._export(componentid, currespath, 'SystemMessageServer%s' % counterSystemMessageServer));
          counterSystemMessageServer = counterSystemMessageServer + 1;
        elif componentid.find("#ExternallyManagedHTTPServer_") != -1:
          returndict = Util.createTypeFolder(respath, "ExternallyManagedHTTPServer", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, ExternallyManagedHTTPServer._export(componentid, currespath, 'ExternallyManagedHTTPServer%s' % counterExternallyManagedHTTPServer));
          counterExternallyManagedHTTPServer = counterExternallyManagedHTTPServer + 1;
        elif componentid.find("#WorkloadManagementServer_") != -1:
          returndict = Util.createTypeFolder(respath, "WorkloadManagementServer", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, WorkloadManagementServer._export(componentid, currespath, 'WorkloadManagementServer%s' % counterWorkloadManagementServer));
          counterWorkloadManagementServer = counterWorkloadManagementServer + 1;
        elif componentid.find("#ExternalFileService_") != -1:
          returndict = Util.createTypeFolder(respath, "ExternalFileService", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, ExternalFileService._export(componentid, currespath, 'ExternalFileService%s' % counterExternalFileService));
          counterExternalFileService = counterExternalFileService + 1;
        elif componentid.find("#ApplicationServer_") != -1:
          returndict = Util.createTypeFolder(respath, "ApplicationServer", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, ApplicationServer._export(componentid, currespath, 'ApplicationServer%s' % counterApplicationServer));
          counterApplicationServer = counterApplicationServer + 1;
        elif componentid.find("#ApplicationContainer_") != -1:
          returndict = Util.createTypeFolder(respath, "ApplicationContainer", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, ApplicationContainer._export(componentid, currespath, 'ApplicationContainer%s' % counterApplicationContainer));
          counterApplicationContainer = counterApplicationContainer + 1;
        elif componentid.find("#WebServer_") != -1:
          returndict = Util.createTypeFolder(respath, "WebServer", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, WebServer._export(componentid, currespath, 'WebServer%s' % counterWebServer));
          counterWebServer = counterWebServer + 1;
        elif componentid.find("#SIPContainer_") != -1:
          returndict = Util.createTypeFolder(respath, "SIPContainer", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, SIPContainer._export(componentid, currespath, 'SIPContainer%s' % counterSIPContainer));
          counterSIPContainer = counterSIPContainer + 1;
        elif componentid.find("#CellManager_") != -1:
          returndict = Util.createTypeFolder(respath, "CellManager", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, CellManager._export(componentid, currespath));
          counterCellManager = counterCellManager + 1;
        elif componentid.find("#Proxy_") != -1:
          returndict = Util.createTypeFolder(respath, "Proxy", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, Proxy._export(componentid, currespath, 'Proxy%s' % counterProxy));
          counterProxy = counterProxy + 1;
        elif componentid.find("#OnDemandRouter_") != -1:
          returndict = Util.createTypeFolder(respath, "OnDemandRouter", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, OnDemandRouter._export(componentid, currespath, 'OnDemandRouter%s' % counterOnDemandRouter));
          counterOnDemandRouter = counterOnDemandRouter + 1;
        elif componentid.find("#ProxyServer_") != -1:
          returndict = Util.createTypeFolder(respath, "ProxyServer", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, ProxyServer._export(componentid, currespath, 'ProxyServer%s' % counterProxyServer));
          counterProxyServer = counterProxyServer + 1;
  return extraObjects;

def createObjIfRole(objid, curjsonobject, currole, threadPoolLookupPath):
  if currole == "WebSphereNodeAgent":
    NodeAgent.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereSecurityServer":
    SecurityServer.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereEJBContainer":
    EJBContainer.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereJobManager":
    JobManager.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereAgent":
    Agent.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereServerComponent":
    ServerComponent.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereWebContainer":
    WebContainer.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereForeignServer":
    ForeignServer.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereSystemMessageServer":
    SystemMessageServer.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereExternallyManagedHTTPServer":
    ExternallyManagedHTTPServer.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereWorkloadManagementServer":
    WorkloadManagementServer.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereExternalFileService":
    ExternalFileService.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereApplicationServer":
    ApplicationServer.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereApplicationContainer":
    ApplicationContainer.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereWebServer":
    WebServer.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereNameServer":
    NameServer.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereSIPContainer":
    SIPContainer.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereCellManager":
    CellManager.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereProxy":
    Proxy.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereOnDemandRouter":
    OnDemandRouter.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSphereProxyServer":
    ProxyServer.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  elif currole == "WebSpherePortletContainer":
    PortletContainer.create(objid, curjsonobject, threadPoolLookupPath);
    return 1;
  return 0;
