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

__name_att__ = "websphere.datareplicationdomain.name"

def export(objid, parentcontainmentpath, parentrespath):

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

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

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


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.datareplicationdomain.name", objid, "name","DataReplicationDomain");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

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

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

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

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

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

  objid = Util.getid(containmentpath);
  if objid == None or len(objid) == 0:
    if Util.__removePartialConfig__ == "false":
      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 DataReplicationDomain on.");
      objid = create(parentid, jsonobject);
  else:
    if Util.__removePartialConfig__ == "true":
      Util.removePartialApply(objid);
      objid = None;
    else:
      update(objid,jsonobject);
  return objid;



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  properties = [];
  Util.addIfNotNone(properties, "name", roleProperties.optString("websphere.datareplicationdomain.name", None));
  print "Creating DataReplicationDomain with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("DataReplicationDomain", parentid, properties);

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

  return objid;

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

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

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.datareplicationdomain.name", None), "name","DataReplicationDomain");
  if len(atts) != 0:
    print "Modifying DataReplicationDomain with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

  defaultDataReplicationSettings = Util.getOptionalAttribute(objid, 'defaultDataReplicationSettings', 'DataReplicationDomain');
  if defaultDataReplicationSettings is not None and len(defaultDataReplicationSettings) > 0:
    Util.remove(defaultDataReplicationSettings);

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