from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from SecurityDomainMember import SecurityDomainMember
from ManagementScope import ManagementScope
from AppSecurity import AppSecurity
from Property import Property

__name_att__ = "websphere.securitydomain.name"

def export(objid, parentcontainmentpath, parentrespath):

  name = Util.getRequiredAttribute(objid, "name", 'SecurityDomain');

  containmentpath = "%(parentconpath)sSecurityDomain:%(name)s/" % {'parentconpath':parentcontainmentpath, 'name':name }
  if not containmentpath.startswith("/"):
    containmentpath = "/" + containmentpath;

  dict = _export(objid, parentrespath);
  dict['conpath'] = containmentpath;
  return dict

def _export(objid, parentrespath):
  Util.pushPathElement('SecurityDomain')

  name = Util.getRequiredAttribute(objid, "name", 'SecurityDomain');


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securitydomain.name", objid, "name","SecurityDomain");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.securitydomain.description", objid, "description","SecurityDomain");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

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

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

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

  i = 0;
  appSecurities = AppSecurity.getAppSecurity(objid);
  for appSecurity in appSecurities:
    if len(appSecurity) > 0:
      returndict = Util.createTypeFolder(respath, "AppSecurity", typeFolders);
      currespath = returndict['path'];
      if returndict.has_key('object'):
        Util.addFromExport(extraObjects, returndict['object']);
      Util.addAllFromExport(extraObjects, AppSecurity._export(appSecurity, currespath, "AppSecurity"));

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.securitydomain.name"):
    raise Exception("Resource role properties does not contain websphere.securitydomain.name!");

  objid = Util.getid(containmentpath);
  if objid == None or len(objid) == 0:
    index = containmentpath.rindex('/',0,len(containmentpath)-2)+1;
    parentconpath = containmentpath[0:index];
    parentid = Util.getid(parentconpath);
    if parentid == None or len(parentid) == 0:
      raise Exception("Parent does not exist to create SecurityDomain on.");
    objid = create(parentid, jsonobject);
  else:
    update(objid,jsonobject);
  return objid;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  if not roleProperties.has("websphere.securitydomain.name"):
    raise Exception("Resource role properties does not contain websphere.securitydomain.name!");
  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.securitydomain.name", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.securitydomain.description", None));
  print "Creating SecurityDomain with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("SecurityDomain", parentid, properties);

  members = Util.parseConfigIdListAttribute(objid, 'members',"SecurityDomain");
  for member in members:
    if len(member) > 0:
      Util.remove(member);

  scopes = Util.parseConfigIdListAttribute(objid, 'memberScopes',"SecurityDomain");
  for scope in scopes:
    if len(scope) > 0:
      Util.remove(scope);

  appSecurities = AppSecurity.getAppSecurity(objid);
  for appSecurity in appSecurities:
    Util.remove(appSecurity);

  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    for curjsonobject in children[:]:
      currole = curjsonobject.getString("roleName");
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if propertyObject == 0:
        if currole == "WebSphereSecurityDomainMember":
          SecurityDomainMember.create(objid, curjsonobject);
        elif currole == "WebSphereManagementScope":
          ManagementScope.create(objid, curjsonobject);
        elif currole == "WebSphereAppSecurity":
          AppSecurity.create(objid, curjsonobject);
  Util.popPathElement('SecurityDomain');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  if not roleProperties.has("websphere.securitydomain.name"):
    raise Exception("Resource role properties does not contain websphere.securitydomain.name!");

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

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

  members = Util.parseConfigIdListAttribute(objid, 'members',"SecurityDomain");
  for member in members:
    if len(member) > 0:
      Util.remove(member);

  scopes = Util.parseConfigIdListAttribute(objid, 'memberScopes',"SecurityDomain");
  for scope in scopes:
    if len(scope) > 0:
      Util.remove(scope);

  appSecurities = AppSecurity.getAppSecurity(objid);
  for appSecurity in appSecurities:
    Util.remove(appSecurity);

  if jsonobject.has('children'):
    children = Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children'));
    for curjsonobject in children[:]:
      currole = curjsonobject.getString("roleName");
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if propertyObject == 0:
        if currole == "WebSphereSecurityDomainMember":
          SecurityDomainMember.create(objid, curjsonobject);
        elif currole == "WebSphereManagementScope":
          ManagementScope.create(objid, curjsonobject);
        elif currole == "WebSphereAppSecurity":
          AppSecurity.create(objid, curjsonobject);
  Util.popPathElement('SecurityDomain');

def getSecurityDomains(objid):
  securityDomains = Util.getAssociatedObjects(objid, "SecurityDomain");
  return securityDomains;

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