###
# Licensed Materials - Property of IBM* and/or HCL**
# (c) Copyright IBM Corporation 2014, 2016, 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 ProtocolProviderRef import ProtocolProviderRef
from utilities import Util

__name_att__ = "websphere.mailsession.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mailsession.mailstoreport", objid, "mailStorePort","MailSession");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mailsession.mailfrom", objid, "mailFrom","MailSession");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mailsession.mailtransportport", objid, "mailTransportPort","MailSession");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mailsession.mailstorehost", objid, "mailStoreHost","MailSession");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mailsession.providertype", objid, "providerType","MailSession");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mailsession.mailtransporthost", objid, "mailTransportHost","MailSession");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mailsession.mailstorepassword", objid, "mailStorePassword","MailSession");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mailsession.jndiname", objid, "jndiName","MailSession");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mailsession.debug", objid, "debug","MailSession");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mailsession.mailstoreuser", objid, "mailStoreUser","MailSession");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mailsession.category", objid, "category","MailSession");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mailsession.description", objid, "description","MailSession");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mailsession.mailtransportuser", objid, "mailTransportUser","MailSession");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mailsession.mailtransportpassword", objid, "mailTransportPassword","MailSession");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mailsession.strict", objid, "strict","MailSession");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.mailsession.name", objid, "name","MailSession");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

  mailStoreProtocol = Util.getOptionalAttribute(objid, 'mailStoreProtocol', 'MailSession');
  if mailStoreProtocol is not None and len(mailStoreProtocol) > 0:
    returndict = Util.createTypeFolder(respath, "ProtocolProviderRef", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, ProtocolProviderRef._export(mailStoreProtocol, currespath, "mailStoreProtocol"));

  mailTransportProtocol = Util.getOptionalAttribute(objid, 'mailTransportProtocol', 'MailSession');
  if mailTransportProtocol is not None and len(mailTransportProtocol) > 0:
    returndict = Util.createTypeFolder(respath, "ProtocolProviderRef", typeFolders);
    currespath = returndict['path'];
    if returndict.has_key('object'):
      Util.addFromExport(extraObjects, returndict['object']);
    Util.addAllFromExport(extraObjects, ProtocolProviderRef._export(mailTransportProtocol, currespath, "mailTransportProtocol"));

  # It seems that the 'provider' attribute is a reference to this MailSession's
  # parent MailProvider and we don't have much control over this reference.
  # We are going to let WebSphere handle/control this attribute
  # automatically instead of us doing something explicitly.

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



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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "mailStorePort", roleProperties.optString("websphere.mailsession.mailstoreport", None));
  Util.addIfNotNone(properties, "mailFrom", roleProperties.optString("websphere.mailsession.mailfrom", None));
  Util.addIfNotNone(properties, "mailTransportPort", roleProperties.optString("websphere.mailsession.mailtransportport", None));
  Util.addIfNotNone(properties, "mailStoreHost", roleProperties.optString("websphere.mailsession.mailstorehost", None));
  Util.addIfNotNone(properties, "providerType", roleProperties.optString("websphere.mailsession.providertype", None));
  Util.addIfNotNone(properties, "mailTransportHost", roleProperties.optString("websphere.mailsession.mailtransporthost", None));
  Util.addIfNotNone(properties, "mailStorePassword", roleProperties.optString("websphere.mailsession.mailstorepassword", None));
  Util.addIfNotNone(properties, "jndiName", roleProperties.optString("websphere.mailsession.jndiname", None));
  Util.addIfNotNone(properties, "debug", roleProperties.optString("websphere.mailsession.debug", None));
  Util.addIfNotNone(properties, "mailStoreUser", roleProperties.optString("websphere.mailsession.mailstoreuser", None));
  Util.addIfNotNone(properties, "category", roleProperties.optString("websphere.mailsession.category", None));
  Util.addIfNotNone(properties, "description", roleProperties.optString("websphere.mailsession.description", None));
  Util.addIfNotNone(properties, "mailTransportUser", roleProperties.optString("websphere.mailsession.mailtransportuser", None));
  Util.addIfNotNone(properties, "mailTransportPassword", roleProperties.optString("websphere.mailsession.mailtransportpassword", None));
  Util.addIfNotNone(properties, "strict", roleProperties.optString("websphere.mailsession.strict", None));
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.mailsession.name", None));
  print "Creating MailSession with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("MailSession", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereProtocolProviderRef":
        pprefRoleProps = curjsonobject.getJSONObject("roleProperties");
        providerType = pprefRoleProps.getString('websphere.protocolproviderref.type');
        if providerType == "STORE":
          attName = "mailStoreProtocol"
        else:
          attName = "mailTransportProtocol"
        ProtocolProviderRef.create(objid, curjsonobject, attName);

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.mailsession.mailstoreport", None), "mailStorePort","MailSession");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.mailsession.mailfrom", None), "mailFrom","MailSession");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.mailsession.mailtransportport", None), "mailTransportPort","MailSession");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.mailsession.mailstorehost", None), "mailStoreHost","MailSession");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.mailsession.providertype", None), "providerType","MailSession");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.mailsession.mailtransporthost", None), "mailTransportHost","MailSession");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.mailsession.mailstorepassword", None), "mailStorePassword","MailSession");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.mailsession.jndiname", None), "jndiName","MailSession");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.mailsession.debug", None), "debug","MailSession");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.mailsession.mailstoreuser", None), "mailStoreUser","MailSession");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.mailsession.category", None), "category","MailSession");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.mailsession.description", None), "description","MailSession");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.mailsession.mailtransportuser", None), "mailTransportUser","MailSession");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.mailsession.mailtransportpassword", None), "mailTransportPassword","MailSession");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.mailsession.strict", None), "strict","MailSession");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.mailsession.name", None), "name","MailSession");
  if len(atts) != 0:
    print "Modifying MailSession with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  Util.unsetAttribute(objid, "mailStoreProtocol", "MailSession");
  Util.unsetAttribute(objid, "mailTransportProtocol", "MailSession");

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString('roleName');
      if currole == "WebSphereProtocolProviderRef":
        pprefRoleProps = curjsonobject.getJSONObject("roleProperties");
        providerType = pprefRoleProps.getString('websphere.protocolproviderref.type');
        if providerType == "STORE":
          attName = "mailStoreProtocol"
        else:
          attName = "mailTransportProtocol"
        ProtocolProviderRef.create(objid, curjsonobject, attName);

  Util.popPathElement('MailSession');
