from org.codehaus.jettison.json import JSONObject, JSONArray
from utilities import Util
from Archive import Archive
from EJBJarFile import EJBJarFile
from WARFile import WARFile
from WARFragmentFile import WARFragmentFile
from EARFile import EARFile
from ApplicationClientFile import ApplicationClientFile
from ModuleFile import ModuleFile
from Container import Container
from ReadOnlyDirectory import ReadOnlyDirectory
from RARFile import RARFile

__name_att__ = None;

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.file.directoryentry", objid, "directoryEntry","File");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.file.uri", objid, "URI","File");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.file.size", objid, "size","File");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.file.lastmodified", objid, "lastModified","File");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.file.originaluri", objid, "originalURI","File");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('File');
  return result;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "directoryEntry", roleProperties.optString("websphere.file.directoryentry", None));
  Util.addIfNotNone(properties, "URI", roleProperties.optString("websphere.file.uri", None));
  Util.addIfNotNone(properties, "size", roleProperties.optString("websphere.file.size", None));
  Util.addIfNotNone(properties, "lastModified", roleProperties.optString("websphere.file.lastmodified", None));
  Util.addIfNotNone(properties, "originalURI", roleProperties.optString("websphere.file.originaluri", None));
  print "Creating File with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("File", parentid, properties);
  Util.popPathElement('File');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.file.directoryentry", None), "directoryEntry","File");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.file.uri", None), "URI","File");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.file.size", None), "size","File");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.file.lastmodified", None), "lastModified","File");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.file.originaluri", None), "originalURI","File");
  if len(atts) != 0:
    print "Modifying File with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

def removeFiles(objid, attributeName, parentType):
  files = Util.parseConfigIdListAttribute(objid, attributeName, parentType);
  if files is not None and len(files) > 0:
    for fileid in files:
      if len(fileid) > 0:
        Util.remove(fileid);

def exportFiles(objid, respath, extraObjects, typeFolders, attributeName, parentType):
  counterArchive = 0;
  counterEJBJarFile = 0;
  counterWARFile = 0;
  counterWARFragmentFile = 0;
  counterEARFile = 0;
  counterApplicationClientFile = 0;
  counterModuleFile = 0;
  counterContainer = 0;
  counterReadOnlyDirectory = 0;
  counterRARFile = 0;

  files = Util.parseConfigIdListAttribute(objid, attributeName, parentType);
  if files is not None and len(files) > 0:
    for fileid in files:
      if len(fileid) > 0:
        if fileid.find("#Archive_") != -1:
          returndict = Util.createTypeFolder(respath, "Archive", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, Archive._export(fileid, currespath, 'Archive%s' % counterArchive));
          counterArchive = counterArchive + 1;
        elif fileid.find("#EJBJarFile_") != -1:
          returndict = Util.createTypeFolder(respath, "EJBJarFile", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, EJBJarFile._export(fileid, currespath, 'EJBJarFile%s' % counterEJBJarFile));
          counterEJBJarFile = counterEJBJarFile + 1;
        elif fileid.find("#WARFile_") != -1:
          returndict = Util.createTypeFolder(respath, "WARFile", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, WARFile._export(fileid, currespath, 'WARFile%s' % counterWARFile));
          counterWARFile = counterWARFile + 1;
        elif fileid.find("#WARFragmentFile_") != -1:
          returndict = Util.createTypeFolder(respath, "WARFragmentFile", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, WARFragmentFile._export(fileid, currespath, 'WARFragmentFile%s' % counterWARFragmentFile));
          counterWARFragmentFile = counterWARFragmentFile + 1;
        elif fileid.find("#EARFile_") != -1:
          returndict = Util.createTypeFolder(respath, "EARFile", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, EARFile._export(fileid, currespath, 'EARFile%s' % counterEARFile));
          counterEARFile = counterEARFile + 1;
        elif fileid.find("#ApplicationClientFile_") != -1:
          returndict = Util.createTypeFolder(respath, "ApplicationClientFile", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, ApplicationClientFile._export(fileid, currespath, 'ApplicationClientFile%s' % counterApplicationClientFile));
          counterApplicationClientFile = counterApplicationClientFile + 1;
        elif fileid.find("#ModuleFile_") != -1:
          returndict = Util.createTypeFolder(respath, "ModuleFile", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, ModuleFile._export(fileid, currespath, 'ModuleFile%s' % counterModuleFile));
          counterModuleFile = counterModuleFile + 1;
        elif fileid.find("#Container_") != -1:
          returndict = Util.createTypeFolder(respath, "Container", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, Container._export(fileid, currespath, 'Container%s' % counterContainer));
          counterContainer = counterContainer + 1;
        elif fileid.find("#ReadOnlyDirectory_") != -1:
          returndict = Util.createTypeFolder(respath, "ReadOnlyDirectory", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, ReadOnlyDirectory._export(fileid, currespath, 'ReadOnlyDirectory%s' % counterReadOnlyDirectory));
          counterReadOnlyDirectory = counterReadOnlyDirectory + 1;
        elif fileid.find("#RARFile_") != -1:
          returndict = Util.createTypeFolder(respath, "RARFile", typeFolders);
          currespath = returndict['path'];
          if returndict.has_key('object'):
            Util.addFromExport(extraObjects, returndict['object']);
          Util.addAllFromExport(extraObjects, RARFile._export(fileid, currespath, 'RARFile%s' % counterRARFile));
          counterRARFile = counterRARFile + 1;

  return extraObjects;

def createObjIfRole(objid, curjsonobject, currole):
  if currole == "WebSphereArchive":
    Archive.create(objid, curjsonobject);
    return 1;
  elif currole == "WebSphereEJBJarFile":
    EJBJarFile.create(objid, curjsonobject);
    return 1;
  elif currole == "WebSphereWARFile":
    WARFile.create(objid, curjsonobject);
    return 1;
  elif currole == "WebSphereWARFragmentFile":
    WARFragmentFile.create(objid, curjsonobject);
    return 1;
  elif currole == "WebSphereEARFile":
    EARFile.create(objid, curjsonobject);
    return 1;
  elif currole == "WebSphereEventApplicationClientFile":
    ApplicationClientFile.create(objid, curjsonobject);
    return 1;
  elif currole == "WebSphereModuleFile":
    ModuleFile.create(objid, curjsonobject);
    return 1;
  elif currole == "WebSphereContainer":
    Container.create(objid, curjsonobject);
    return 1;
  elif currole == "WebSphereReadOnlyDirectory":
    ReadOnlyDirectory.create(objid, curjsonobject);
    return 1;
  elif currole == "WebSphereRARFile":
    RARFile.create(objid, curjsonobject);
    return 1;
  return 0;

