###
# 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 URL import URL;
from utilities import Util;

__name_att__ = "websphere.urlprovider.name"

def export(objid, parentcontainmentpath, parentrespath):

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

  containmentpath = "%(parentconpath)sURLProvider:%(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('URLProvider')

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.urlprovider.name", objid, "name","URLProvider");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.urlprovider.classpath", objid, "classpath","URLProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.urlprovider.providertype", objid, "providerType","URLProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.urlprovider.streamhandlerclassname", objid, "streamHandlerClassName","URLProvider");
  Util.addAttributePathPropertyToJson(roleProperties, "websphere.urlprovider.nativepath", objid, "nativepath","URLProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.urlprovider.description", objid, "description","URLProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.urlprovider.protocol", objid, "protocol","URLProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.urlprovider.isolatedclassloader", objid, "isolatedClassLoader","URLProvider");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  urls = URL.getURLs(objid);
  urlNamesCnt = {};
  if urls is not None and len(urls) > 0:
    for url in urls:
      if url is not None and url.strip() != "":
        # Used to tell when URL name is duplicated
        urlName = Util.getRequiredAttribute(url, "name", 'URL');
        if urlName in urlNamesCnt.keys():
          urlNamesCnt[urlName] = urlNamesCnt[urlName] + 1;
        else:
          urlNamesCnt[urlName] = 1;

        returndict = Util.createTypeFolder(respath, "URL", typeFolders);
        currespath = returndict['path'];
        if returndict.has_key('object'):
          Util.addFromExport(extraObjects, returndict['object']);
        Util.addAllFromExport(extraObjects, URL._export(url, currespath, urlNamesCnt[urlName]));

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

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has("websphere.urlprovider.name"):
    raise Exception("Resource role properties does not contain websphere.urlprovider.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 URLProvider on.");
    objid = create(parentid, jsonobject);
  else:
    update(objid,jsonobject);
  return objid;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.urlprovider.name", None));
  Util.addPathProperty(properties, "classpath", roleProperties.optString("websphere.urlprovider.classpath", None));
  Util.addIfNotNone(properties, "providerType", roleProperties.optString("websphere.urlprovider.providertype", None));
  Util.addIfNotNone(properties, "streamHandlerClassName", roleProperties.optString("websphere.urlprovider.streamhandlerclassname", None));
  Util.addPathProperty(properties, "nativepath", roleProperties.optString("websphere.urlprovider.nativepath", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.urlprovider.description", None));
  Util.addIfNotNone(properties, "protocol", roleProperties.optString("websphere.urlprovider.protocol", None));
  Util.addIfNotNone(properties, "isolatedClassLoader", roleProperties.optString("websphere.urlprovider.isolatedclassloader", None));
  print "Creating URLProvider with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("URLProvider", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereURL":
        URL.create(objid, curjsonobject);

  Util.popPathElement('URLProvider');
  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.urlprovider.name", None), "name","URLProvider");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.urlprovider.classpath", None), "classpath","URLProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.urlprovider.providertype", None), "providerType","URLProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.urlprovider.streamhandlerclassname", None), "streamHandlerClassName","URLProvider");
  Util.addPathAttIfChanged(objid, atts, roleProperties.optString("websphere.urlprovider.nativepath", None), "nativepath","URLProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.urlprovider.description", None), "description","URLProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.urlprovider.protocol", None), "protocol","URLProvider");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.urlprovider.isolatedclassloader", None), "isolatedClassLoader","URLProvider");
  if len(atts) != 0:
    print "Modifying URLProvider with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  urls = URL.getURLs(objid);
  if urls is not None and len(urls) > 0:
    for url in urls:
      if url is not None and url.strip() != "":
        Util.remove(url);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereURL":
        URL.create(objid, curjsonobject);

  Util.popPathElement('URLProvider');
