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

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

  roleProperties = JSONObject();
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.wsscheduleref.name", objid, "name", "WSSchedule");
  
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('WSScheduleRef');
  return result;

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

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

  name = roleProperties.getString('websphere.wsscheduleref.name');

  wsscheduleId = None;
  wsschedules = Util.getid("/WSSchedule:/").splitlines();
  if len(wsschedules) > 0:
    for wsschedule in wsschedules:
      if len(wsschedule) > 0:
        wsschedulename = Util.getRequiredAttribute(wsschedule, "name", "WSSchedule");
        if (name == wsschedulename):
          wsscheduleId = wsschedule;
          break;
  
  if wsscheduleId is None or len(wsscheduleId) < 1:
    raise Exception("Could not find wsschedule named %(name)s" % { 'name': name } );

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