#- Licensed Materials - Property of IBM Corp.
#- IBM UrbanCode Deploy
#- (c) Copyright IBM Corporation 2016. All Rights Reserved.
#-
#- U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
#- GSA ADP Schedule Contract with IBM Corp.

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

__name_att__ = None;


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

  if parentrespath == "/":
    parentrespath = "";
  respath = "%(parentrespath)s/%(name)s" % { 'parentrespath':parentrespath, 'name':resname }
  if not respath.startswith("/"):
    respath = "/" + respath;

  exportedObject = JSONObject();
  exportedObject.put("name", resname);
  exportedObject.put("path", respath);
  exportedObject.put("teamMappings", JSONArray());
  exportedObject.put("inheritTeam", "true");
  exportedObject.put("description", "Discovered WebSphereProtocolProviderRef");
  exportedObject.put("roleName", "WebSphereProtocolProviderRef");

  roleProperties = JSONObject();
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.protocolproviderref.classname", objid, "classname", "ProtocolProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.protocolproviderref.protocol", objid, "protocol", "ProtocolProvider");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.protocolproviderref.type", objid, "type", "ProtocolProvider");

  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  if len(extraObjects) != 0:
    result['extraObjects'] = extraObjects;
  Util.popPathElement('ProtocolProviderRef');
  return result;

def create(parentid, jsonobject, parentAtt):
  Util.pushPathElement('ProtocolProviderRef')

  if not jsonobject.has("roleProperties"):
    raise Exception("ProtocolProviderRef resource has no role properties!");

  roleProperties = jsonobject.getJSONObject("roleProperties");
  if not roleProperties.has('websphere.protocolproviderref.classname'):
    raise Exception("ProtocolProviderRef resource has no property named websphere.protocolproviderref.classname!");
  if not roleProperties.has('websphere.protocolproviderref.protocol'):
    raise Exception("ProtocolProviderRef resource has no property named websphere.protocolproviderref.protocol!");
  if not roleProperties.has('websphere.protocolproviderref.type'):
    raise Exception("ProtocolProviderRef resource has no property named websphere.protocolproviderref.type!");

  refclassname = roleProperties.getString('websphere.protocolproviderref.classname')
  refprotocol = roleProperties.getString('websphere.protocolproviderref.protocol')
  reftype = roleProperties.getString('websphere.protocolproviderref.type')

  scopeRegEx = re.search('(\(.*\|)', parentid);
  parentScope = scopeRegEx.group(1);
  #print "parentScope is %(parentScope)s" % { 'parentScope':parentScope };
  protocolProviderId = None;
  protocolProviders = Util.getid("/ProtocolProvider:/").splitlines();
  if len(protocolProviders) > 0:
    for protocolProvider in protocolProviders:
      #print "protocolProvider is %(protocolProvider)s" % { 'protocolProvider':protocolProvider };
      if len(protocolProvider) > 0 and protocolProvider.find(parentScope) >= 0:
        protocol = Util.getRequiredAttribute(protocolProvider, "protocol", "ProtocolProvider" );
        classname = Util.getRequiredAttribute(protocolProvider, "classname", "ProtocolProvider" );
        ptype = Util.getOptionalAttribute(protocolProvider, "type", "ProtocolProvider" );

        if (refclassname == classname and refprotocol == protocol and reftype == ptype):
          protocolProviderId = protocolProvider;
          break;

  if protocolProviderId is None or len(protocolProviderId) < 1:
    raise Exception("Could not find protocol provider with classname %(name)s and protocol %(protocol)s" % { 'name':refclassname, 'protocol':refprotocol } );

  properties = [];
  properties.append([parentAtt, protocolProviderId]);
  Log.debug(properties);
  Log.debug(parentid);
  print "Creating ProtocolProviderRef to %(id)s for attribute %(att)s" % { 'id':protocolProviderId, 'att':parentAtt };
  objid = Util.modify(parentid, properties);
  Log.debug("Finished Creating ProtocolProviderRef to %(id)s for attribute %(att)s" % { 'id':protocolProviderId, 'att':parentAtt });
  Util.popPathElement('ProtocolProviderRef');
