###
# Licensed Materials - Property of IBM* and/or HCL**
# (c) Copyright IBM Corporation 2014, 2015, 2017. All Rights Reserved.
# (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
#
# U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
# GSA ADP Schedule Contract with IBM Corp.
#
# * Trademark of International Business Machines
# ** Trademark of HCL Technologies Limited

from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from Property import Property
from TrustAssociation import TrustAssociation
from SingleSignon import SingleSignon
from DigestAuthentication import DigestAuthentication

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customauthmechanism.simpleauthconfig", objid, "simpleAuthConfig","CustomAuthMechanism");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customauthmechanism.authcontextimplclass", objid, "authContextImplClass","CustomAuthMechanism");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customauthmechanism.authconfig", objid, "authConfig","CustomAuthMechanism");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customauthmechanism.iscredentialforwardable", objid, "isCredentialForwardable","CustomAuthMechanism");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customauthmechanism.oid", objid, "OID","CustomAuthMechanism");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.customauthmechanism.authvalidationconfig", objid, "authValidationConfig","CustomAuthMechanism");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"CustomAuthMechanism");
  trust = Util.getOptionalAttribute(objid, 'trustAssociation', 'CustomAuthMechanism');
  if trust is not None and len(trust) > 0:
    returndict = Util.createTypeFolder(respath, 'TrustAssociation', typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, TrustAssociation._export(trust, currespath, "TrustAssociation"));

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

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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "simpleAuthConfig", roleProperties.optString("websphere.customauthmechanism.simpleauthconfig", None));
  Util.addIfNotNone(properties, "authContextImplClass", roleProperties.optString("websphere.customauthmechanism.authcontextimplclass", None));
  Util.addIfNotNone(properties, "authConfig", roleProperties.optString("websphere.customauthmechanism.authconfig", None));
  Util.addIfNotNone(properties, "isCredentialForwardable", roleProperties.optString("websphere.customauthmechanism.iscredentialforwardable", None));
  Util.addIfNotNone(properties, "OID", roleProperties.optString("websphere.customauthmechanism.oid", None));
  Util.addIfNotNone(properties, "authValidationConfig", roleProperties.optString("websphere.customauthmechanism.authvalidationconfig", None));
  print "Creating CustomAuthMechanism with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("CustomAuthMechanism", parentid, properties);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereTrustAssociation":
        TrustAssociation.create(objid, curjsonobject);
      elif currole == "WebSphereSingleSignon":
        SingleSignon.create(objid, curjsonobject);
      elif currole == "WebSphereDigestAuthentication":
        DigestAuthentication.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('CustomAuthMechanism');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customauthmechanism.simpleauthconfig", None), "simpleAuthConfig","CustomAuthMechanism");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customauthmechanism.authcontextimplclass", None), "authContextImplClass","CustomAuthMechanism");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customauthmechanism.authconfig", None), "authConfig","CustomAuthMechanism");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customauthmechanism.iscredentialforwardable", None), "isCredentialForwardable","CustomAuthMechanism");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customauthmechanism.oid", None), "OID","CustomAuthMechanism");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.customauthmechanism.authvalidationconfig", None), "authValidationConfig","CustomAuthMechanism");
  if len(atts) != 0:
    print "Modifying CustomAuthMechanism with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Property.removeProperties(objid, 'properties',"CustomAuthMechanism");
  digest = Util.getOptionalAttribute(objid, 'digestAuthentication', 'CustomAuthMechanism');
  if digest is not None and len(digest) > 0:
    Util.remove(digest);
  trust = Util.getOptionalAttribute(objid, 'trustAssociation', 'CustomAuthMechanism');
  if trust is not None and len(trust) > 0:
    Util.remove(trust);
  sso = Util.getOptionalAttribute(objid, 'singleSignon', 'CustomAuthMechanism');
  if sso is not None and len(sso) > 0:
    Util.remove(sso);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereTrustAssociation":
        TrustAssociation.create(objid, curjsonobject);
      elif currole == "WebSphereSingleSignon":
        SingleSignon.create(objid, curjsonobject);
      elif currole == "WebSphereDigestAuthentication":
        DigestAuthentication.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('CustomAuthMechanism');
