from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from WASConfLog import Log
from EndPoint import EndPoint
from OverlayEndpoint import OverlayEndpoint
from utilities import Util

__name_att__ = None;

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


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

  roleProperties = JSONObject();

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

  endpoint = Util.getOptionalAttribute(objid, 'endPoint', 'LSDConnection');
  if endpoint is not None and len(endpoint) > 0:
    if endpoint.find("#EndPoint_") != -1:
      returndict = Util.createTypeFolder(respath, "EndPoint", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, EndPoint._export(endpoint, currespath, 'endPoint'));
    elif endpoint.find("#OverlayEndpoint_") != -1:
      returndict = Util.createTypeFolder(respath, "OverlayEndpoint", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, OverlayEndpoint._export(endpoint, currespath, 'endPoint'));

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereEndPoint":
        name = curjsonobject.getString('name');
        if name == "endPoint":
          ep = Util.getOptionalAttribute(objid, 'endPoint', 'LSDConnection');
          if ep is not None and len(ep) > 0:
            EndPoint.update(ep, curjsonobject)
          else:
            Log.log("Unable to update endPoint in LSDConnection");
        else:
          Log.log("Warning: Invalid attribute name " + name + " specified for WebSphereEndPoint. Expected endPoint");
      elif currole == "WebSphereOverlayEndpoint":
        name = curjsonobject.getString('name');
        if name == "endPoint":
          oep = Util.getOptionalAttribute(objid, 'endPoint', 'LSDConnection');
          if oep is not None and len(oep) > 0:
            OverlayEndpoint.update(oep, curjsonobject);
          else:
            Log.log("Unable to update endPoint in LSDConnection");
        else:
          Log.log("Warning: Invalid attribute name " + name + " specified for WebSphereOverlayEndpoint. Expected endPoint"); 
  Util.popPathElement('LSDConnection');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereEndPoint":
        name = curjsonobject.getString('name');
        if name == "endPoint":
          ep = Util.getOptionalAttribute(objid, 'endPoint', 'LSDConnection');
          if ep is not None and len(ep) > 0:
            EndPoint.update(ep, curjsonobject)
          else:
            Log.log("Unable to update endPoint in LSDConnection");
        else:
          Log.log("Warning: Invalid attribute name " + name + " specified for WebSphereEndPoint. Expected endPoint");
      elif currole == "WebSphereOverlayEndpoint":
        name = curjsonobject.getString('name');
        if name == "endPoint":
          oep = Util.getOptionalAttribute(objid, 'endPoint', 'LSDConnection');
          if oep is not None and len(oep) > 0:
            OverlayEndpoint.update(oep, curjsonobject);
          else:
            Log.log("Unable to update endPoint in LSDConnection");
        else:
          Log.log("Warning: Invalid attribute name " + name + " specified for WebSphereOverlayEndpoint. Expected endPoint");
  Util.popPathElement('LSDConnection');
