#- 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 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('SWAMAuthentication')


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.swamauthentication.simpleauthconfig", objid, "simpleAuthConfig","SWAMAuthentication");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.swamauthentication.authcontextimplclass", objid, "authContextImplClass","SWAMAuthentication");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.swamauthentication.authconfig", objid, "authConfig","SWAMAuthentication");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.swamauthentication.iscredentialforwardable", objid, "isCredentialForwardable","SWAMAuthentication");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.swamauthentication.oid", objid, "OID","SWAMAuthentication");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.swamauthentication.authvalidationconfig", objid, "authValidationConfig","SWAMAuthentication");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};
  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"SWAMAuthentication");

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "simpleAuthConfig", roleProperties.optString("websphere.swamauthentication.simpleauthconfig", None));
  Util.addIfNotNone(properties, "authContextImplClass", roleProperties.optString("websphere.swamauthentication.authcontextimplclass", None));
  Util.addIfNotNone(properties, "authConfig", roleProperties.optString("websphere.swamauthentication.authconfig", None));
  Util.addIfNotNone(properties, "isCredentialForwardable", roleProperties.optString("websphere.swamauthentication.iscredentialforwardable", None));
  Util.addIfNotNone(properties, "OID", roleProperties.optString("websphere.swamauthentication.oid", None));
  Util.addIfNotNone(properties, "authValidationConfig", roleProperties.optString("websphere.swamauthentication.authvalidationconfig", None));
  print "Creating SWAMAuthentication with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("SWAMAuthentication", 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('SWAMAuthentication');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  Property.removeProperties(objid, 'properties',"SWAMAuthentication");
  digest = Util.getOptionalAttribute(objid, 'digestAuthentication', 'SWAMAuthentication');
  if digest is not None and len(digest) > 0:
    Util.remove(digest);
  trust = Util.getOptionalAttribute(objid, 'trustAssociation', 'SWAMAuthentication');
  if trust is not None and len(trust) > 0:
    Util.remove(trust);
  sso = Util.getOptionalAttribute(objid, 'singleSignon', 'SWAMAuthentication');
  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('SWAMAuthentication');
