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

__name_att__ = None;


def _export(parentrespath, propName, propValue):
  Util.pushPathElement('RepositoryCustomProperty')

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

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

  roleProperties = JSONObject();

  Util.addToJsonIfNotNone(roleProperties, "name", propName);
  Util.addToJsonIfNotNone(roleProperties, "value", propValue);

  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

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

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  propName = roleProperties.optString("name", None);
  propValue = roleProperties.optString("value", None);
  setIdMgrCustomPropertyParams = '[-id "' + repo + '" -name ' + propName + ' -value ' + propValue + ']';
  Log.debug("Running command to add repository custom property: AdminTask.setIdMgrCustomProperty(" + setIdMgrCustomPropertyParams + ")");
  Util.setIdMgrCustomProperty(setIdMgrCustomPropertyParams);
  Util.popPathElement('RepositoryCustomProperty');

def remove(repo, propName):
  # There is no remove command for some reason
  # The custom property can be removed by setting the value to null
  setIdMgrCustomPropertyParams = '[-id "' + repo + '" -name ' + propName + ' -value ]';
  Log.debug("Running command to remove repository custom property: AdminTask.setIdMgrCustomProperty(" + setIdMgrCustomPropertyParams + ")");
  Util.setIdMgrCustomProperty(setIdMgrCustomPropertyParams);

