from org.codehaus.jettison.json import JSONObject, JSONArray
from utilities import Util
from StateManageable import StateManageable
from Security import Security
from ClusterMember import ClusterMember

__name_att__ = "websphere.cluster"

def export(objid, parentcontainmentpath, parentrespath):

  name = Util.getRequiredAttribute(objid, "name", 'ServerCluster');

  containmentpath = "%(parentconpath)sServerCluster:%(name)s/" % {'parentconpath':parentcontainmentpath, 'name':name }
  if not containmentpath.startswith("/"):
    containmentpath = "/" + containmentpath;

  exportdict = _export(objid, parentrespath);
  exportdict['conpath'] = containmentpath;
  return exportdict

def _export(objid, parentrespath):
  Util.pushPathElement('ServerCluster')

  name = Util.getRequiredAttribute(objid, "name", 'ServerCluster');


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servercluster.preferlocal", objid, "preferLocal","ServerCluster");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servercluster.serveriotimeoutretry", objid, "serverIOTimeoutRetry","ServerCluster");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servercluster.nodegroupname", objid, "nodeGroupName","ServerCluster");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servercluster.shortname", objid, "shortName","ServerCluster");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servercluster.uniqueid", objid, "uniqueId","ServerCluster");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servercluster.servertype", objid, "serverType","ServerCluster");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servercluster.clusteraddress", objid, "clusterAddress","ServerCluster");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servercluster.prefetchdwlmtable", objid, "prefetchDWLMTable","ServerCluster");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servercluster.description", objid, "description","ServerCluster");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servercluster.enableha", objid, "enableHA","ServerCluster");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servercluster.enableclusteraddressing", objid, "enableClusterAddressing","ServerCluster");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.servercluster.jsfprovider", objid, "jsfProvider","ServerCluster");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.cluster", objid, "name","ServerCluster");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  
  stateManagement = Util.getRequiredAttribute(objid, 'stateManagement',"ServerCluster");
  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"));    

  members = Util.parseConfigIdListAttribute(objid, 'members', "ServerCluster");
  for member in members:
    if len(member) > 0:
      returndict = Util.createTypeFolder(respath, "ClusterMember", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, ClusterMember._export(member, currespath));

  secfolderretdict = Util.createTypeFolder(respath, "Security", typeFolders);
  secresfolpath = secfolderretdict['path'];
  if secfolderretdict.has_key('object'):
    Util.addFromExport(extraObjects, secfolderretdict['object']);
  Util.addAllFromExport(extraObjects, Security._export(objid, secresfolpath, "Security"));

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



def doImport(containmentpath, roleName, jsonobject):
  if not jsonobject.has("roleProperties"):
    raise Exception("ServerCluster resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.cluster"):
    raise Exception("Resource role properties does not contain websphere.cluster!");

  objid = Util.getid(containmentpath);
  if objid == None or len(objid) == 0:
    index = containmentpath.rindex('/',0,len(containmentpath)-2)+1;
    parentconpath = containmentpath[0:index];
    parentid = Util.getid(parentconpath);
    if parentid == None or len(parentid) == 0:
      raise Exception("Parent does not exist to create ServerCluster on.");
    objid = create(parentid, jsonobject);
  else:
    update(objid,jsonobject);
  return objid;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  if not roleProperties.has("websphere.cluster"):
    raise Exception("Resource role properties does not contain websphere.cluster!");

  properties = [];
  Util.addIfNotNone(properties, "preferLocal", roleProperties.optString("websphere.servercluster.preferlocal", None));
  Util.addIfNotNone(properties, "serverIOTimeoutRetry", roleProperties.optString("websphere.servercluster.serveriotimeoutretry", None));
  Util.addIfNotNone(properties, "nodeGroupName", roleProperties.optString("websphere.servercluster.nodegroupname", None));
  Util.addIfNotNone(properties, "shortName", roleProperties.optString("websphere.servercluster.shortname", None));
  #Util.addIfNotNone(properties, "uniqueId", roleProperties.optString("websphere.servercluster.uniqueid", None));
  Util.addIfNotNone(properties, "serverType", roleProperties.optString("websphere.servercluster.servertype", None));
  Util.addIfNotNone(properties, "clusterAddress", roleProperties.optString("websphere.servercluster.clusteraddress", None));
  Util.addIfNotNone(properties, "prefetchDWLMTable", roleProperties.optString("websphere.servercluster.prefetchdwlmtable", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.servercluster.description", None));
  Util.addIfNotNone(properties, "enableHA", roleProperties.optString("websphere.servercluster.enableha", None));
  Util.addIfNotNone(properties, "enableClusterAddressing", roleProperties.optString("websphere.servercluster.enableclusteraddressing", None));
  Util.addIfNotNone(properties, "jsfProvider", roleProperties.optString("websphere.servercluster.jsfprovider", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.cluster", None));
  print "Creating ServerCluster with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("ServerCluster", parentid, properties);
  
  stateManagement = Util.getRequiredAttribute(objid, 'stateManagement',"ServerCluster");
  if stateManagement is not None and len(stateManagement) > 0:
    Util.remove(stateManagement);      

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");    
      if currole == "WebSphereStateManageable":
        StateManageable.create(objid, curjsonobject);
      elif currole == "WebSphereClusterMember":
        ClusterMember.create(objid, curjsonobject);
      elif currole == "WebSphereSecurity":
        Security.update(objid, curjsonobject);
  Util.popPathElement('ServerCluster');
  
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  if not roleProperties.has("websphere.cluster"):
    raise Exception("Resource role properties does not contain websphere.cluster!");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.servercluster.preferlocal", None), "preferLocal","ServerCluster");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.servercluster.serveriotimeoutretry", None), "serverIOTimeoutRetry","ServerCluster");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.servercluster.nodegroupname", None), "nodeGroupName","ServerCluster");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.servercluster.shortname", None), "shortName","ServerCluster");
  #Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.servercluster.uniqueid", None), "uniqueId","ServerCluster");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.servercluster.servertype", None), "serverType","ServerCluster");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.servercluster.clusteraddress", None), "clusterAddress","ServerCluster");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.servercluster.prefetchdwlmtable", None), "prefetchDWLMTable","ServerCluster");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.servercluster.description", None), "description","ServerCluster");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.servercluster.enableha", None), "enableHA","ServerCluster");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.servercluster.enableclusteraddressing", None), "enableClusterAddressing","ServerCluster");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.servercluster.jsfprovider", None), "jsfProvider","ServerCluster");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.cluster", None), "name","ServerCluster");
  if len(atts) != 0:
    print "Modifying ServerCluster with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  stateManagement = Util.getRequiredAttribute(objid, 'stateManagement',"ServerCluster");
  if stateManagement is not None and len(stateManagement) > 0:
    Util.remove(stateManagement);      

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");    
      if currole == "WebSphereStateManageable":
        StateManageable.create(objid, curjsonobject);
      elif currole == "WebSphereClusterMember":
        # We can't delete all ClusterMembers and recreate them.
        # Instead, we need to update existing ones.
        # However, multiple cluster members can have the same name.
        # So, we have to do some ugly stuff to see if our ClusterMember already exist.
        # If they do exist, update them. If they don't exist, create them.
        cmobjid = "";
        roleProperties = curjsonobject.getJSONObject("roleProperties");
        targetNodeName = roleProperties.optString("websphere.clustermember.nodename", None);
        targetMemberName = roleProperties.optString("websphere.clustermember.membername", None);
        if targetNodeName != None and len(targetNodeName) > 0:
          # get all ClusterMembers
          members = Util.parseConfigIdListAttribute(objid, 'members', 'ServerCluster');
          for member in members:
            # see if the nodeName and membername attribute matches
            actualNodeName = Util.getRequiredAttribute(member, "nodeName", 'ClusterMember');
            actualMemberName = Util.getRequiredAttribute(member, "memberName", 'ClusterMember');
            if actualNodeName == targetNodeName and targetMemberName == actualMemberName:
              cmobjid = member;
              break;
        if cmobjid != "":
          ClusterMember.update(cmobjid, curjsonobject);
        else:
          ClusterMember.create(objid, curjsonobject);
      elif currole == "WebSphereSecurity":
        Security.update(objid, curjsonobject);
  Util.popPathElement('ServerCluster');
