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

__name_att__ = None;


def _export(parentrespath, name, resname):
  Util.pushPathElement('ThreadPoolRef')


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

  roleProperties = JSONObject();

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has('websphere.threadpoolref.name'):
    raise Exception("ThreadPoolRef resource has property named websphere.threadpoolref.name!");

  threadpoolname = roleProperties.getString('websphere.threadpoolref.name')

  threadpoolpath = "%(cur)sThreadPool:%(name)s/" % { 'cur':threadPoolLookupPath, 'name': threadpoolname };
  threadpoolid = Util.getid(threadpoolpath);
  
  if threadpoolid is None or len(threadpoolid) < 1:
    raise Exception("Could not find thread pool named %(name)s in lookup path %(path)s" % { 'name':threadpoolname, 'path':threadPoolLookupPath });

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