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

__name_att__ = None;


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

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

  roleProperties = JSONObject();
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.referenceableref.classname", objid, "classname", "Referenceable");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.referenceableref.factoryclassname", objid, "factoryClassname", "Referenceable");

  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('ReferenceableRef');
  return result;

def create(parentid, jsonobject, parentAtt):
  Util.pushPathElement('ReferenceableRef');

  if not jsonobject.has("roleProperties"):
    raise Exception("ReferenceableRef resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has('websphere.referenceableref.classname'):
    raise Exception("ReferenceableRef resource has no property named websphere.referenceableref.classname!");
  if not roleProperties.has('websphere.referenceableref.factoryclassname'):
    raise Exception("ReferenceableRef resource has no property named websphere.referenceableref.factoryclassname!");

  classname = roleProperties.getString('websphere.referenceableref.classname');
  factoryClassname = roleProperties.getString('websphere.referenceableref.factoryclassname');

  referenceableId = None;
  resourceEnvironmentProviderId = Util.getRequiredAttribute(parentid, "provider", "ResourceEnvEntry");
  referenceables = ResourceEnvironmentProvider.getReferenceables(resourceEnvironmentProviderId);
  if len(referenceables) > 0:
    for referenceable in referenceables:
      if len(referenceable) > 0:
        refclassname = Util.getRequiredAttribute(referenceable, "classname", "Referenceable");
        reffactoryclassname = Util.getRequiredAttribute(referenceable, "factoryClassname", "Referenceable");

        if ((classname == refclassname) and (factoryClassname == reffactoryclassname)):
          referenceableId = referenceable;
          break;

  if referenceableId is None or len(referenceableId) < 1:
    raise Exception("Could not find referenceable with classname %(name)s and factoryClassname %(factoryname)s" % { 'name':name, 'factoryname':factoryClassname } );

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