from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from WASConfLog import Log;
from utilities import Util

__name_att__ = None;


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

  if parentrespath == "/":
    parentrespath = "";
  respath = "%(parentrespath)s/%(name)s" % { 'parentrespath':parentrespath, 'name':resname }
  if not respath.startswith("/"):
    respath = "/" + respath;

  exportedObject = JSONObject();
  exportedObject.put("name", resname);
  exportedObject.put("path", respath);
  exportedObject.put("teamMappings", JSONArray());
  exportedObject.put("inheritTeam", "true");
  exportedObject.put("description", "Discovered WebSphereKeyStoreRef");
  exportedObject.put("roleName", "WebSphereKeyStoreRef");

  roleProperties = JSONObject();
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.keystoreref.name", objid, "name","KeyStore");
  
  scopeName = None;
  managementScope = Util.getOptionalAttribute(objid, 'managementScope', 'KeyStore');
  if managementScope is not None and len(managementScope) > 0:
    scopeName = Util.getOptionalAttribute(managementScope, 'scopeName', 'ManagementScope');
    if scopeName is not None and len(scopeName) > 0:
      Util.addToJsonIfNotNone(roleProperties, "websphere.keystoreref.scopename", scopeName);
  
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('KeyStoreRef');
  return result;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has('websphere.keystoreref.name'):
    raise Exception("KeyStoreRef resource has no property named websphere.keystoreref.name!");
  if not roleProperties.has('websphere.keystoreref.scopename'):
    raise Exception("KeyStoreRef resource has no property named websphere.keystoreref.scopename!");

  keyStoreName = roleProperties.getString('websphere.keystoreref.name');
  keyStoreScopeName = roleProperties.getString('websphere.keystoreref.scopename');

  keyStoreId = None;
  keyStores = Util.getid("/KeyStore:/").splitlines();
  if len(keyStores) > 0:
    for keyStore in keyStores:
      if len(keyStore) > 0:
        name = Util.getRequiredAttribute(keyStore, "name", "KeyStore" );
        scopeName = None;
        managementScope = Util.getOptionalAttribute(keyStore, 'managementScope', 'KeyStore');
        if managementScope is not None and len(managementScope) > 0:
          scopeName = Util.getOptionalAttribute(managementScope, 'scopeName', 'ManagementScope');

        if (keyStoreName == name and keyStoreScopeName == scopeName):
          keyStoreId = keyStore;
          break;
  
  if keyStoreId is None or len(keyStoreId) < 1:
    raise Exception("Could not find keystore named %(name)s with management scopename of %(scopeName)s" % { 'name':keyStoreName, 'scopeName':keyStoreScopeName } );

  properties = [];
  properties.append([parentAtt, keyStoreId]);
  Log.debug(properties);
  Log.debug(parentid);
  print "Creating KeyStoreRef to %(id)s for attribute %(att)s" % { 'id':keyStoreId, 'att':parentAtt };
  objid = Util.modify(parentid, properties);
  Log.debug("Finished Creating KeyStoreRef to %(id)s for attribute %(att)s" % { 'id':keyStoreId, 'att':parentAtt });
  Util.popPathElement('KeyStoreRef');
