###
# Licensed Materials - Property of IBM* and/or HCL**
# (c) Copyright IBM Corporation 2014, 2015, 2017. All Rights Reserved.
# (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
#
# U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
# GSA ADP Schedule Contract with IBM Corp.
#
# * Trademark of International Business Machines
# ** Trademark of HCL Technologies Limited

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

__name_att__ = "websphere.url.name"

def export(objid, parentcontainmentpath, parentrespath):

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

  containmentpath = "%(parentconpath)sURL:%(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, nameCount):
  Util.pushPathElement('URL')

  # WAS allows creating URL objects with the same name at the same scope
  # so we handle that by making the UCD resource name be 'name-jndiname'.
  urlName = Util.getRequiredAttribute(objid, "name", 'URL');
  if nameCount > 1:
    jndiName = Util.getRequiredAttribute(objid, "jndiName", 'URL');
    name = urlName + "-" + jndiName;
  else:
    name = urlName;

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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.url.spec", objid, "spec","URL");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.url.name", objid, "name","URL");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.url.description", objid, "description","URL");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.url.category", objid, "category","URL");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.url.providertype", objid, "providerType","URL");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.url.jndiname", objid, "jndiName","URL");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('URL');
  return result;

def doImportPartial(containmentpath, roleName, jsonobject):
  doImport(containmentpath, roleName, jsonobject);

def doImport(containmentpath, roleName, jsonobject):
  url = Util.getid(containmentpath);

  if url == None or url == "":
    if Util.__removePartialConfig__ == "false":
      index = containmentpath.rindex('/',0,len(containmentpath)-2)+1;
      parentconpath = containmentpath[0:index];
      parentid = Util.getid(parentconpath);
      url = create(parentid, jsonobject);
  else:
    if Util.__removePartialConfig__ == "true":
      Util.removePartialApply(url);
      url = None;
    else:
      update(url, jsonobject);
  return url;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "spec", roleProperties.optString("websphere.url.spec", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.url.name", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.url.description", None));
  Util.addIfNotNone(properties, "category", roleProperties.optString("websphere.url.category", None));
  Util.addIfNotNone(properties, "providerType", roleProperties.optString("websphere.url.providertype", None));
  Util.addIfNotNone(properties, "jndiName", roleProperties.optString("websphere.url.jndiname", None));
  print "Creating URL with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("URL", parentid, properties);
  Util.popPathElement('URL');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.url.spec", None), "spec","URL");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.url.name", None), "name","URL");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.url.description", None), "description","URL");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.url.category", None), "category","URL");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.url.providertype", None), "providerType","URL");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.url.jndiname", None), "jndiName","URL");
  if len(atts) != 0:
    print "Modifying URL with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Util.popPathElement('URL');

def getURLs(objid):
  URLs = Util.getAssociatedObjects(objid, "URL");
  return URLs;
