#- Licensed Materials - Property of IBM Corp.
#- IBM UrbanCode Deploy
#- (c) Copyright IBM Corporation 2014, 2015. All Rights Reserved.
#-
#- U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
#- GSA ADP Schedule Contract with IBM Corp.

from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from AuthenticationMechanism import AuthenticationMechanism
from ConnectionDefinition import ConnectionDefinition

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.outboundresourceadapter.transactionsupport", objid, "transactionSupport","OutboundResourceAdapter");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.outboundresourceadapter.reauthenticationsupport", objid, "reauthenticationSupport","OutboundResourceAdapter");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  i = 0;
  mechanisms = Util.parseConfigIdListAttribute(objid, 'authenticationMechanisms', 'OutboundResourceAdapter');
  for mech in mechanisms:
    if len(mech) > 0:
      returndict = Util.createTypeFolder(respath, "AuthenticationMechanism", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, AuthenticationMechanism._export(mech, currespath, "AuthenticationMechanism%s" % i));
      i = i + 1;

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

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


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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "transactionSupport", roleProperties.optString("websphere.outboundresourceadapter.transactionsupport", None));
  Util.addIfNotNone(properties, "reauthenticationSupport", roleProperties.optString("websphere.outboundresourceadapter.reauthenticationsupport", None));
  print "Creating OutboundResourceAdapter with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("OutboundResourceAdapter", parentid, properties);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereAuthenticationMechanism":
        AuthenticationMechanism.create(objid, curjsonobject);
      elif currole == "WebSphereConnectionDefinition":
        ConnectionDefinition.create(objid, curjsonobject);
  Util.popPathElement('OutboundResourceAdapter');


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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  mechanisms = Util.parseConfigIdListAttribute(objid, 'authenticationMechanisms', 'OutboundResourceAdapter');
  for mech in mechanisms:
    if len(mech) > 0:
      Util.remove(mech);

  connDefs = Util.parseConfigIdListAttribute(objid, 'connectionDefinitions', 'OutboundResourceAdapter');
  for connDef in connDefs:
    if len(connDef) > 0:
      Util.remove(connDef);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereAuthenticationMechanism":
        AuthenticationMechanism.create(objid, curjsonobject);
      elif currole == "WebSphereConnectionDefinition":
        ConnectionDefinition.create(objid, curjsonobject);
  Util.popPathElement('OutboundResourceAdapter');
