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

__name_att__ = None;

def _export(objid, parentrespath, name = ""):
  Util.pushPathElement('HTTPInboundChannelLogging')


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

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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannellogging.enableaccesslogging", objid, "enableAccessLogging","HTTPInboundChannelLogging");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannellogging.accesslogformat", objid, "accessLogFormat","HTTPInboundChannelLogging");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannellogging.enableerrorlogging", objid, "enableErrorLogging","HTTPInboundChannelLogging");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannellogging.enablefrcalogging", objid, "enableFRCALogging","HTTPInboundChannelLogging");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannellogging.frcalogformat", objid, "frcaLogFormat","HTTPInboundChannelLogging");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.httpinboundchannellogging.errorloglevel", objid, "errorLogLevel","HTTPInboundChannelLogging");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  accessLog = Util.getOptionalAttribute(objid, 'accessLog', 'HTTPInboundChannelLogging');
  if accessLog is not None and len(accessLog) > 0:
    returndict = Util.createTypeFolder(respath, "LogFile", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, LogFile._export(accessLog, currespath, 'accessLog'));

  errorLog = Util.getOptionalAttribute(objid, 'errorLog', 'HTTPInboundChannelLogging');
  if errorLog is not None and len(errorLog) > 0:
    returndict = Util.createTypeFolder(respath, "LogFile", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, LogFile._export(errorLog, currespath, 'errorLog'));

  frcaLog = Util.getOptionalAttribute(objid, 'frcaLog', 'HTTPInboundChannelLogging');
  if frcaLog is not None and len(frcaLog) > 0:
    returndict = Util.createTypeFolder(respath, "LogFile", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, LogFile._export(frcaLog, currespath, 'frcaLog'));

  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('HTTPInboundChannelLogging');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "enableAccessLogging", roleProperties.optString("websphere.httpinboundchannellogging.enableaccesslogging", None));
  Util.addIfNotNone(properties, "accessLogFormat", roleProperties.optString("websphere.httpinboundchannellogging.accesslogformat", None));
  Util.addIfNotNone(properties, "enableErrorLogging", roleProperties.optString("websphere.httpinboundchannellogging.enableerrorlogging", None));
  Util.addIfNotNone(properties, "enableFRCALogging", roleProperties.optString("websphere.httpinboundchannellogging.enablefrcalogging", None));
  Util.addIfNotNone(properties, "frcaLogFormat", roleProperties.optString("websphere.httpinboundchannellogging.frcalogformat", None));
  Util.addIfNotNone(properties, "errorLogLevel", roleProperties.optString("websphere.httpinboundchannellogging.errorloglevel", None));
  print "Creating HTTPInboundChannelLogging with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("HTTPInboundChannelLogging", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereLogFile":
        name = curjsonobject.getString('name');
        if name == "accessLog":
          LogFile.create(objid, curjsonobject, "accessLog");
        elif name == "errorLog":
          LogFile.create(objid, curjsonobject, "errorLog");
        elif name == "frcaLog":
          LogFile.create(objid, curjsonobject, "frcaLog");
        else:
          print ("Warning: " + name + " is an invalid LogFile attribute name for the HTTPInboundChannelogging object.  " +
                 "Expected accessLog, errorLog or frcaLog.");
  Util.popPathElement('HTTPInboundChannelLogging');

def update(objid,jsonobject):
  Util.pushPathElement('HTTPInboundChannelLogging')
  if not jsonobject.has("roleProperties"):
    raise Exception("HTTPInboundChannelLogging resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannellogging.enableaccesslogging", None), "enableAccessLogging","HTTPInboundChannelLogging");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannellogging.accesslogformat", None), "accessLogFormat","HTTPInboundChannelLogging");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannellogging.enableerrorlogging", None), "enableErrorLogging","HTTPInboundChannelLogging");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannellogging.enablefrcalogging", None), "enableFRCALogging","HTTPInboundChannelLogging");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannellogging.frcalogformat", None), "frcaLogFormat","HTTPInboundChannelLogging");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.httpinboundchannellogging.errorloglevel", None), "errorLogLevel","HTTPInboundChannelLogging");
  if len(atts) != 0:
    print "Modifying HTTPInboundChannelLogging with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

    Util.modify(objid, atts);
  else:   
    print "HTTPInboundChannelLogging configuration up to date.";

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereLogFile":
        name = curjsonobject.getString('name');
        if name == "accessLog":
          accessLog = Util.getOptionalAttribute(objid, 'accessLog', 'HTTPInboundChannelLogging');
          if accessLog is not None and len(accessLog) > 0:
            Util.remove(accessLog);
          LogFile.create(objid, curjsonobject, "accessLog");
        elif name == "errorLog":
          errorLog = Util.getOptionalAttribute(objid, 'errorLog', 'HTTPInboundChannelLogging');
          if errorLog is not None and len(errorLog) > 0:
            Util.remove(errorLog);
          LogFile.create(objid, curjsonobject, "errorLog");
        elif name == "frcaLog":
          frcaLog = Util.getOptionalAttribute(objid, 'frcaLog', 'HTTPInboundChannelLogging');
          if frcaLog is not None and len(frcaLog) > 0:
            Util.remove(frcaLog);
          LogFile.create(objid, curjsonobject, "frcaLog");
        else:
          print ("Warning: " + name + " is an invalid LogFile attribute name for the HTTPInboundChannelogging object.  " +
                 "Expected accessLog, errorLog or frcaLog.");
  Util.popPathElement('HTTPInboundChannelLogging');
