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('CertificateRef')

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

  roleProperties = JSONObject();
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.certificateref.alias", objid, "alias","Certificate");
  
  keyStoreName = None;
  keyStore = Util.getOptionalAttribute(objid, 'keyStore', 'Certificate');
  if keyStore is not None and len(keyStore) > 0:
    keyStoreName = Util.getOptionalAttribute(keyStore, 'name', 'KeyStore');
    if keyStoreName is not None and len(keyStoreName) > 0:
      Util.addToJsonIfNotNone(roleProperties, "websphere.certificateref.keystorename", keyStoreName);
  
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('CertificateRef');
  return result;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has('websphere.certificateref.alias'):
    raise Exception("CertificateRef resource has no property named websphere.certificateref.alias!");
  if not roleProperties.has('websphere.certificateref.keystorename'):
    raise Exception("CertificateRef resource has no property named websphere.certificateref.keystorename!");

  alias = roleProperties.getString('websphere.certificateref.alias');
  keyStoreName = roleProperties.getString('websphere.certificateref.keystorename');

  certificateId = None;
  certificates = Util.getid("/Certificate:/").splitlines();
  if len(certificates) > 0:
    for certificate in certificates:
      if len(certificate) > 0:
        certificateAlias = Util.getRequiredAttribute(certificate, "alias", "Certificate" );
        certificateKeyStoreName = None;
        keyStore = Util.getOptionalAttribute(certificate, 'keyStore', 'Certificate');
        if keyStore is not None and len(keyStore) > 0:
          certificateKeyStoreName = Util.getOptionalAttribute(keyStore, 'name', 'KeyStore');

        if (alias == certificateAlias and keyStoreName == certificateKeyStoreName):
          certificateId = certificate;
          break;
  
  if certificateId is None or len(certificateId) < 1:
    raise Exception("Could not find certificate named %(alias)s with keystore name of %(name)s" % { 'alias':alias, 'name':keyStoreName } );

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