/**
 *
 *  Licensed to the Apache Software Foundation (ASF) under one
 *  or more contributor license agreements.  See the NOTICE file
 *  distributed with this work for additional information
 *  regarding copyright ownership.  The ASF licenses this file
 *  to you under the Apache License, Version 2.0 (the
 *  "License"); you may not use this file except in compliance
 *  with the License.  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing,
 *  software distributed under the License is distributed on an
 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 *  KIND, either express or implied.  See the License for the
 *  specific language governing permissions and limitations
 *  under the License.
 */
package test.sdo21.tests.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.List;

import test.sdo21.framework.TestHelper;

import commonj.sdo.DataObject;
import commonj.sdo.Property;
import commonj.sdo.Type;
import commonj.sdo.helper.HelperContext;

public class CTSUtil {
  /**
   * Convenience method for creating a unique name that can be used for a
   * property or type.
   * 
   * @return String containing a unique name
   */
  public static DataObject createTypeDef(String uri, String name, boolean open,
      HelperContext helperContext) {
    DataObject typeDef = helperContext.getDataFactory().create("commonj.sdo",
        "Type");
    typeDef.set("uri", uri);
    typeDef.set("name", name);
    typeDef.set("open", Boolean.valueOf(open));
    return typeDef;
  }

  public static DataObject createPropertyDef(DataObject typeDef, String propertyName,
      Type type, boolean isMany, boolean isContainment) {
    DataObject propertyDef = typeDef.createDataObject("property");
    propertyDef.set("name", propertyName);
    propertyDef.set("type", type);
    propertyDef.set("many", isMany);
    propertyDef.set("containment", isContainment);
    return propertyDef;
  }

  public static DataObject createPropertyDef(DataObject typeDef, String propertyName,
      String typeName, boolean isMany, boolean isContainment,
      HelperContext helperContext) {
    int pos = typeName.indexOf('#');
    String uri = "";
    String name;
    if (pos > 0) {
      uri = typeName.substring(0, pos);
      name = typeName.substring(pos + 1);
    } else {
      name = typeName;
    }
    Type propertyType = helperContext.getTypeHelper().getType(uri, name);
    return createPropertyDef(typeDef, propertyName, propertyType, isMany,
        isContainment);
  }

  public static String createUniqueName() {
    return "name-" + System.currentTimeMillis() + "-"
        + ((int) (1000 * Math.random()));
  }
  
  /**
   * areEqualTypes is used to determine of two Types are equivalent even if
   * not identically equal. The names of the Types are compared, as well as
   * the Types of each of the Properties making up the Type.
   * 
   * @param type1
   * @param type2
   * @return
   */
  public static boolean areEqualTypes(Type type1, Type type2) {
      List properties1, properties2;
      Property property1, property2;
      int size = 0, j = 0, k;
      boolean found;

      // Equivalent Types have the same name

      if (!(type1.getName().equals(type2.getName())))
          return false;

      // Equivalent Types have the same number of Properties

      properties1 = type1.getProperties();
      properties2 = type2.getProperties();
      size = properties1.size();

      if (size != properties2.size())
          return false;

      // Equivalent Types have Properties of the same name and Type

      for (int i = 0; i < size; i++) {
          property1 = (Property)properties1.get(i);
          k = 0;
          found = false;

          while (k < size && !found) {
              // j is used to prevent the initial Properties in properties2
              // from being checked every time
              // j is particularly useful when the Types have Properties in
              // the order

              property2 = (Property)properties2.get((k + j) % size);

              if (property1.getName().equals(property2.getName())) {
                  j++;
                  found = true;

                  // Should not use recursion here to compare the Types of the
                  // Properties, because
                  // it is possible that a Type may recursively contain
                  // itself.

                  if (!(property1.getType().getName().equals(property2.getType().getName())))
                      return false;
              }
              k++;
          }
          if (!found)
              return false;
      }
      return true;
  }
  
  /**
   * Uses the XMLHelper to serialize the input DataObject
   * 
   * @param dataObject
   * @param baos
   * @param helperContexgt
   * @throws IOException
   */
  public static void serializeDataObjectXML(DataObject dataObject, ByteArrayOutputStream baos, HelperContext helperContext) throws IOException {
      Type type = dataObject.getType();
      helperContext.getXMLHelper().save(dataObject, type.getURI(), type.getName(), baos);
  }
  
  /**
   * Uses the XMLHelper to deserialize the input XML file
   * 
   * @param bais
   * @param helperContext
   * @return
   * @throws IOException
   * @throws ClassNotFoundException
   */
  public static DataObject deserializeDataObjectXML(ByteArrayInputStream bais, HelperContext helperContext) throws IOException, ClassNotFoundException {
      return helperContext.getXMLHelper().load(bais).getRootObject();
  }
  
  /**
   * Uses Java serialization to serialize the input DataObject
   * 
   * @param dataObject
   * @param baos
   * @param helperContext
   * @throws IOException
   */
  public static void serializeDataObjectJava(TestHelper testHelper, DataObject dataObject, ByteArrayOutputStream baos, HelperContext helperContext) throws IOException {
      ObjectOutputStream out = testHelper.createObjectOutputStream(baos, helperContext);
      out.writeObject(dataObject);
      out.close();
  }

  /**
   * Uses Java deserialization to deserialize the input XML file
   * 
   * @param bais
   * @param helperContext
   * @return
   * @throws IOException
   * @throws ClassNotFoundException
   */
  public static DataObject deserializeDataObjectJava(TestHelper testHelper, ByteArrayInputStream bais, HelperContext helperContext) throws IOException, ClassNotFoundException {
      ObjectInputStream input = testHelper.createObjectInputStream(bais, helperContext);
      DataObject dataObject = (DataObject)input.readObject();
      input.close();
      return dataObject;
  }


  
}
