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

__name_att__ = None;

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


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

  roleProperties = JSONObject();

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

  extraObjects = Property.exportProperties(objid, respath, extraObjects, typeFolders, 'properties',"HTTPAccessLoggingService");

  accessLog = Util.getOptionalAttribute(objid, 'accessLog', 'HTTPAccessLoggingService');
  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', 'HTTPAccessLoggingService');
  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', 'HTTPAccessLoggingService');
  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('HTTPAccessLoggingService');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      propertyObject = 0;
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if (propertyObject == 0):
        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 HTTPAccessLoggingService object.  " +
                   "Expected accessLog, errorLog or frcaLog.");
  Util.popPathElement('HTTPAccessLoggingService');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

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

  Property.removeProperties(objid, 'properties',"HTTPAccessLoggingService");

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      propertyObject = 0;
      propertyObject = Property.createObjIfRole(objid, curjsonobject, currole);
      if (propertyObject == 0):
        if currole == "WebSphereLogFile":
          name = curjsonobject.getString('name');
          if name == "accessLog":
            accessLog = Util.getOptionalAttribute(objid, 'accessLog', 'HTTPAccessLoggingService');
            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', 'HTTPAccessLoggingService');
            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', 'HTTPAccessLoggingService');
            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 HTTPAccessLoggingService object.  " +
                   "Expected accessLog, errorLog or frcaLog.");
  Util.popPathElement('HTTPAccessLoggingService');
