###
# 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 KeySetGroupRef import KeySetGroupRef
from TrustAssociation import TrustAssociation
from SingleSignon import SingleSignon
from DigestAuthentication import DigestAuthentication
from Key import Key

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ltpa.simpleauthconfig", objid, "simpleAuthConfig","LTPA");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ltpa.authcontextimplclass", objid, "authContextImplClass","LTPA");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ltpa.authconfig", objid, "authConfig","LTPA");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ltpa.iscredentialforwardable", objid, "isCredentialForwardable","LTPA");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ltpa.timeout", objid, "timeout","LTPA");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ltpa.oid", objid, "OID","LTPA");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ltpa.password", objid, "password","LTPA", 1);
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.ltpa.authvalidationconfig", objid, "authValidationConfig","LTPA");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"LTPA");

  keySetGroup = Util.getOptionalAttribute(objid, 'keySetGroup', 'LTPA');
  if keySetGroup is not None and len(keySetGroup) > 0:
    returndict = Util.createTypeFolder(respath, "KeySetGroupRef", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, KeySetGroupRef._export(keySetGroup, currespath, Util.getRequiredAttribute(keySetGroup, 'name', 'KeySetGroup')));

  trust = Util.getOptionalAttribute(objid, 'trustAssociation', 'LTPA');
  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', 'LTPA');
  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', 'LTPA');
  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"));

  privateKey = Util.getOptionalAttribute(objid, 'private', 'LTPA');
  if privateKey is not None and len(privateKey) > 0:
    returndict = Util.createTypeFolder(respath, 'Key', typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, Key._export(privateKey, currespath, "Private"));

  publicKey = Util.getOptionalAttribute(objid, 'public', 'LTPA');
  if publicKey is not None and len(publicKey) > 0:
    returndict = Util.createTypeFolder(respath, 'Key', typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, Key._export(publicKey, currespath, "Public"));

  sharedKey = Util.getOptionalAttribute(objid, 'shared', 'LTPA');
  if sharedKey is not None and len(sharedKey) > 0:
    returndict = Util.createTypeFolder(respath, 'Key', typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, Key._export(sharedKey, currespath, "Shared"));

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

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

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "simpleAuthConfig", roleProperties.optString("websphere.ltpa.simpleauthconfig", None));
  Util.addIfNotNone(properties, "authContextImplClass", roleProperties.optString("websphere.ltpa.authcontextimplclass", None));
  Util.addIfNotNone(properties, "authConfig", roleProperties.optString("websphere.ltpa.authconfig", None));
  Util.addIfNotNone(properties, "isCredentialForwardable", roleProperties.optString("websphere.ltpa.iscredentialforwardable", None));
  Util.addIfNotNone(properties, "timeout", roleProperties.optString("websphere.ltpa.timeout", None));
  Util.addIfNotNone(properties, "OID", roleProperties.optString("websphere.ltpa.oid", None));
  Util.addIfNotNone(properties, "password", roleProperties.optString("websphere.ltpa.password", None));
  Util.addIfNotNone(properties, "authValidationConfig", roleProperties.optString("websphere.ltpa.authvalidationconfig", None));
  print "Creating LTPA with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("LTPA", parentid, properties);
  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if (propertyObject == 1):
        continue;
      if currole == "WebSphereKeySetGroupRef":
        KeySetGroupRef.create(objid, curjsonobject, "keySetGroup");
      elif currole == "WebSphereTrustAssociation":
        TrustAssociation.create(objid, curjsonobject);
      elif currole == "WebSphereSingleSignon":
        SingleSignon.create(objid, curjsonobject);
      elif currole == "WebSphereDigestAuthentication":
        DigestAuthentication.create(objid, curjsonobject);
      elif currole == "WebSphereKey":
        # Not sure if I need to distinguish between private, public, and shared
        # keys when creating
        Key.create(objid, curjsonobject);
  Util.popPathElement('LTPA');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  Property.removeProperties(objid, 'properties',"LTPA");
  digest = Util.getOptionalAttribute(objid, 'digestAuthentication', 'LTPA');
  if digest is not None and len(digest) > 0:
    Util.remove(digest);
  trust = Util.getOptionalAttribute(objid, 'trustAssociation', 'LTPA');
  if trust is not None and len(trust) > 0:
    Util.remove(trust);
  sso = Util.getOptionalAttribute(objid, 'singleSignon', 'LTPA');
  if sso is not None and len(sso) > 0:
    Util.remove(sso);
  publicKey = Util.getOptionalAttribute(objid, 'public', 'LTPA');
  if publicKey is not None and len(publicKey) > 0:
    Util.remove(publicKey);
  privateKey = Util.getOptionalAttribute(objid, 'private', 'LTPA');
  if privateKey is not None and len(privateKey) > 0:
    Util.remove(privateKey);
  sharedKey = Util.getOptionalAttribute(objid, 'shared', 'LTPA');
  if sharedKey is not None and len(sharedKey) > 0:
    Util.remove(sharedKey);

  Util.unsetAttribute(objid, "keySetGroup", "LTPA");

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if (propertyObject == 1):
        continue;
      if currole == "WebSphereKeySetGroupRef":
        KeySetGroupRef.create(objid, curjsonobject, "keySetGroup");
      elif currole == "WebSphereTrustAssociation":
        TrustAssociation.create(objid, curjsonobject);
      elif currole == "WebSphereSingleSignon":
        SingleSignon.create(objid, curjsonobject);
      elif currole == "WebSphereDigestAuthentication":
        DigestAuthentication.create(objid, curjsonobject);
      elif currole == "WebSphereKey":
        # Not sure if I need to distinguish between private, public, and shared
        # keys when creating
        Key.create(objid, curjsonobject);
  Util.popPathElement('LTPA');
