###
# 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
from Filter import Filter

__name_att__ = None;

def _export(objid, parentrespath, name = ""):
  Util.pushPathElement('SPNEGO')
  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 WebSphereSPNEGO");
  exportedObject.put("roleName", "WebSphereSPNEGO");

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.spnego.simpleauthconfig", objid, "simpleAuthConfig","SPNEGO");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.spnego.allowappauthmethodfallback", objid, "allowAppAuthMethodFallback","SPNEGO");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.spnego.authcontextimplclass", objid, "authContextImplClass","SPNEGO");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.spnego.authconfig", objid, "authConfig","SPNEGO");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.spnego.iscredentialforwardable", objid, "isCredentialForwardable","SPNEGO");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.spnego.enabled", objid, "enabled","SPNEGO");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.spnego.oid", objid, "OID","SPNEGO");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.spnego.authvalidationconfig", objid, "authValidationConfig","SPNEGO");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"SPNEGO");
  trust = Util.getOptionalAttribute(objid, 'trustAssociation', 'SPNEGO');
  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', 'SPNEGO');
  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', 'SPNEGO');
  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"));

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

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

def doImportPartial(containmentpath, roleName, jsonobject):
  return doImport(containmentpath, roleName, jsonobject);

def doImport(containmentpath, roleName, jsonobject):

  spnego = Util.getid(containmentpath);

  if spnego == None or spnego == "":
    if Util.__removePartialConfig__ == "false":
      index = containmentpath.rindex('/',0,len(containmentpath)-2)+1;
      parentconpath = containmentpath[0:index];
      parentid = Util.getid(parentconpath);
      spnego = create(parentid, jsonobject);
  else:
    if Util.__removePartialConfig__ == "true":
      Util.removePartialApply(spnego);
      spnego = None;
    else:
      update(spnego, jsonobject);
  return spnego;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "simpleAuthConfig", roleProperties.optString("websphere.spnego.simpleauthconfig", None));
  Util.addIfNotNone(properties, "allowAppAuthMethodFallback", roleProperties.optString("websphere.spnego.allowappauthmethodfallback", None));
  Util.addIfNotNone(properties, "authContextImplClass", roleProperties.optString("websphere.spnego.authcontextimplclass", None));
  Util.addIfNotNone(properties, "authConfig", roleProperties.optString("websphere.spnego.authconfig", None));
  Util.addIfNotNone(properties, "isCredentialForwardable", roleProperties.optString("websphere.spnego.iscredentialforwardable", None));
  Util.addIfNotNone(properties, "enabled", roleProperties.optString("websphere.spnego.enabled", None));
  Util.addIfNotNone(properties, "OID", roleProperties.optString("websphere.spnego.oid", None));
  Util.addIfNotNone(properties, "authValidationConfig", roleProperties.optString("websphere.spnego.authvalidationconfig", None));
  print "Creating SPNEGO with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("SPNEGO", 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);
      elif currole == "WebSphereFilter":
        Filter.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('SPNEGO');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

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


  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);
      elif currole == "WebSphereFilter":
        Filter.create(objid, curjsonobject);
      else:
        propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
  Util.popPathElement('SPNEGO');
