from org.codehaus.jettison.json import JSONObject, JSONArray
import sys;
from utilities import Util
from DRSPartition import DRSPartition
from DRSConnectionPool import DRSConnectionPool
from DRSSerialization import DRSSerialization
from SecureSocketLayer import SecureSocketLayer

__name_att__ = None;

def _export(objid, parentrespath, name = ""):
  Util.pushPathElement('DataReplication')


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

  roleProperties = JSONObject();

  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.datareplication.requesttimeout", objid, "requestTimeout","DataReplication");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.datareplication.encryptiontype", objid, "encryptionType","DataReplication");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.datareplication.usessl", objid, "useSSL","DataReplication");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.datareplication.userid", objid, "userId","DataReplication");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.datareplication.encryptionkeyvalue", objid, "encryptionKeyValue","DataReplication");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.datareplication.messagebrokername", objid, "messageBrokerName","DataReplication");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.datareplication.password", objid, "password","DataReplication");
  Util.addAttributeToJsonIfNotNone(roleProperties, "websphere.datareplication.numberofreplicas", objid, "numberOfReplicas","DataReplication");
  exportedObject.put("roleProperties", roleProperties);
  result = { 'object': exportedObject, 'respath':respath }
  extraObjects = [];
  typeFolders = {};

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

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

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

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

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



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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  properties = [];
  Util.addIfNotNone(properties, "requestTimeout", roleProperties.optString("websphere.datareplication.requesttimeout", None));
  Util.addIfNotNone(properties, "encryptionType", roleProperties.optString("websphere.datareplication.encryptiontype", None));
  Util.addIfNotNone(properties, "useSSL", roleProperties.optString("websphere.datareplication.usessl", None));
  Util.addIfNotNone(properties, "userId", roleProperties.optString("websphere.datareplication.userid", None));
  Util.addIfNotNone(properties, "encryptionKeyValue", roleProperties.optString("websphere.datareplication.encryptionkeyvalue", None));
  Util.addIfNotNone(properties, "messageBrokerName", roleProperties.optString("websphere.datareplication.messagebrokername", None));
  Util.addIfNotNone(properties, "password", roleProperties.optString("websphere.datareplication.password", None));
  Util.addIfNotNone(properties, "numberOfReplicas", roleProperties.optString("websphere.datareplication.numberofreplicas", None));
  print "Creating DataReplication with attributes";
  for prop in properties:
    print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };
  objid = Util.create("DataReplication", parentid, properties);

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereDRSPartition":
        DRSPartition.create(objid, curjsonobject);
      elif currole == "WebSphereDRSConnectionPool":
        DRSConnectionPool.create(objid, curjsonobject);
      elif currole == "WebSphereDRSSerialization":
        DRSSerialization.create(objid, curjsonobject);
      elif currole == "WebSphereSecureSocketLayer":
        SecureSocketLayer.create(objid, curjsonobject);
  Util.popPathElement('DataReplication');

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

  roleProperties = jsonobject.getJSONObject("roleProperties");

  atts = [];
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.datareplication.requesttimeout", None), "requestTimeout","DataReplication");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.datareplication.encryptiontype", None), "encryptionType","DataReplication");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.datareplication.usessl", None), "useSSL","DataReplication");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.datareplication.userid", None), "userId","DataReplication");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.datareplication.encryptionkeyvalue", None), "encryptionKeyValue","DataReplication");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.datareplication.messagebrokername", None), "messageBrokerName","DataReplication");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.datareplication.password", None), "password","DataReplication");
  Util.addAttIfChanged(objid, atts, roleProperties.optString("websphere.datareplication.numberofreplicas", None), "numberOfReplicas","DataReplication");
  if len(atts) != 0:
    print "Modifying DataReplication with attributes:"
    for prop in atts:
      print "%(name)s = %(value)s" % { 'name': prop[0], 'value': prop[1] };

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

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

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

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

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

  if jsonobject.has('children'):
    for curjsonobject in Util.getHighestChildrenWithRole(jsonobject.getJSONArray('children')):
      currole = curjsonobject.getString("roleName");
      if currole == "WebSphereDRSPartition":
        DRSPartition.create(objid, curjsonobject);
      elif currole == "WebSphereDRSConnectionPool":
        DRSConnectionPool.create(objid, curjsonobject);
      elif currole == "WebSphereDRSSerialization":
        DRSSerialization.create(objid, curjsonobject);
      elif currole == "WebSphereSecureSocketLayer":
        SecureSocketLayer.create(objid, curjsonobject);
  Util.popPathElement('DataReplication');
