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

__name_att__ = "websphere.virtualhost.name"

def export(objid, parentcontainmentpath, parentrespath):

  name = Util.getRequiredAttribute(objid, "name", 'VirtualHost');

  containmentpath = "%(parentconpath)sVirtualHost:%(name)s/" % {'parentconpath':parentcontainmentpath, 'name':name }
  if not containmentpath.startswith("/"):
    containmentpath = "/" + containmentpath;

  dict = _export(objid, parentrespath);
  dict['conpath'] = containmentpath;
  return dict

def _export(objid, parentrespath):
  Util.pushPathElement('VirtualHost')

  name = Util.getRequiredAttribute(objid, "name", 'VirtualHost');


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.virtualhost.name", objid, "name","VirtualHost");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  aliases = Util.parseConfigIdListAttribute(objid, 'aliases',"VirtualHost");
  mimes = Util.parseConfigIdListAttribute(objid, 'mimeTypes',"VirtualHost");
  aliasString = '';
  mimesString = '';
  first = 0;
  for alias in aliases:
    if first == 0:
      first = 1;
    else:
      aliasString = "%s\n" % aliasString;
    host = Util.getRequiredAttribute(alias, 'hostname', 'HostAlias');
    port = Util.getRequiredAttribute(alias, 'port', 'HostAlias');
    aliasString = "%(cur)s%(host)s->%(port)s" % { 'cur':aliasString, 'host':host, 'port':port};

  Util.addToJsonIfNotNone(roleProperties, 'websphere.virtualhost.aliases', aliasString);

  first = 0;
  for mime in mimes:
    if first == 0:
      first = 1;
    else:
      mimesString = "%s\n" % mimesString;
    type = Util.getRequiredAttribute(mime, 'type', 'MimeEntry');
    exts = Util.getOptionalAttribute(mime, 'extensions', 'MimeEntry');
    mimesString = "%(cur)s%(type)s->%(exts)s" % { 'cur':mimesString, 'type':type, 'exts':exts };

  Util.addToJsonIfNotNone(roleProperties, 'websphere.virtualhost.mimetypes', mimesString);
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('VirtualHost');
  return result;



def doImport(containmentpath, roleName, jsonobject):
  if not jsonobject.has("roleProperties"):
    raise Exception("VirtualHost resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.virtualhost.name"):
    raise Exception("Resource role properties does not contain websphere.virtualhost.name!");

  objid = Util.getid(containmentpath);
  if objid == None or len(objid) == 0:
    index = containmentpath.rindex('/',0,len(containmentpath)-2)+1;
    parentconpath = containmentpath[0:index];
    parentid = Util.getid(parentconpath);
    if parentid == None or len(parentid) == 0:
      raise Exception("Parent does not exist to create VirtualHost on.");
    objid = create(parentid, jsonobject);
  else:
    update(objid,jsonobject);
  return objid;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  if not roleProperties.has("websphere.virtualhost.name"):
    raise Exception("Resource role properties does not contain websphere.virtualhost.name!");

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.virtualhost.name", None));
  print "Creating VirtualHost with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("VirtualHost", parentid, properties);

  mimes = Util.parseConfigIdListAttribute(objid, 'mimeTypes',"VirtualHost");
  for mime in mimes:
    Util.remove(mime);

  if roleProperties.has('websphere.virtualhost.aliases'):
    aliases = roleProperties.getString('websphere.virtualhost.aliases').splitlines();
    for alias in aliases:
      if alias is not None and len(alias) > 2:
        parts = alias.split("->", 2);
        host = parts[0];
        port = parts[1];
        Log.log("Creating HostAlias with Host %(host)s and port %(port)s" % { 'host':host, 'port':port });
        Util.create("HostAlias", objid, [['hostname',host],['port',port]]);

  if roleProperties.has('websphere.virtualhost.mimetypes'):
    aliases = roleProperties.getString('websphere.virtualhost.mimetypes').splitlines();
    for alias in aliases:
      if alias is not None and len(alias) > 2:
        parts = alias.split("->", 2);
        type = parts[0];
        exts = parts[1];
        Log.log("Creating MimeEntry with type %(host)s and exensions %(port)s" % { 'host':type, 'port':exts });
        Util.create("MimeEntry", objid, [['type',type],['extensions',exts]]);
  Util.popPathElement('VirtualHost');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  if not roleProperties.has("websphere.virtualhost.name"):
    raise Exception("Resource role properties does not contain websphere.virtualhost.name!");

  virtualHostName = roleProperties.getString('websphere.virtualhost.name')

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.virtualhost.name", None), "name","VirtualHost");
  if len(atts) != 0:
    print "Modifying VirtualHost with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  aliases = Util.parseConfigIdListAttribute(objid, 'aliases',"VirtualHost");
  mimes = Util.parseConfigIdListAttribute(objid, 'mimeTypes',"VirtualHost");

  for alias in aliases:
    Util.remove(alias);

  for mime in mimes:
    Util.remove(mime);

  if roleProperties.has('websphere.virtualhost.aliases'):
    aliases = roleProperties.getString('websphere.virtualhost.aliases').splitlines();
    for alias in aliases:
      if alias is not None and len(alias) > 2:
        if alias.find("->") == -1:
          raise Exception(("The websphere.virtualhost.aliases value for Virtual Host " + virtualHostName + " is "
                           "in an invalid format. A virtual host alias should be in the format host->port. "
                           "Multiple virtual host aliases should be separated by \n. The value of "
                           "websphere.virtualhost.aliases was " + str(alias)));
        else:
          parts = alias.split("->", 2);
          host = parts[0];
          port = parts[1];
          Log.log("Creating HostAlias with Host %(host)s and port %(port)s" % { 'host':host, 'port':port });
          Util.create("HostAlias", objid, [['hostname',host],['port',port]]);

  if roleProperties.has('websphere.virtualhost.mimetypes'):
    aliases = roleProperties.getString('websphere.virtualhost.mimetypes').splitlines();
    for alias in aliases:
      if alias is not None and len(alias) > 2:
        parts = alias.split("->", 2);
        type = parts[0];
        exts = parts[1];
        Log.log("Creating MimeEntry with type %(host)s and exensions %(port)s" % { 'host':type, 'port':exts });
        Util.create("MimeEntry", objid, [['type',type],['extensions',exts]]);
  Util.popPathElement('VirtualHost');
