/*
 *  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.
 *  
 *  $Rev$  $Date$
 */
package test.sdo21.tests.api.DataObject;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;

import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

import test.sdo21.tests.TestData.StandardFactory;
import test.sdo21.tests.api.CTSConsistencyBase;

import commonj.sdo.DataObject;
import commonj.sdo.Property;
import commonj.sdo.Sequence;
import commonj.sdo.Type;
import commonj.sdo.helper.DataFactory;

/**
 * Tests for proper updates to DataObject and their value changes due to the
 * updates.
 */
public abstract class DataObjectConsistencyBase extends CTSConsistencyBase {


    /**
     * testActiveUpdatingList verifies that updates made to a List returned from
     * a DataObject are reflected in the DataObject and vice versa.
     * @throws Exception
     */
    @Test
    public void testActiveUpdatingList() throws Exception {
        DataObject root = factory.createTestData(getScope(), StandardFactory.API_TYPE);
        DataObject child1 = factory.createTestData(getScope(), StandardFactory.API_TYPE);
        DataObject child2 = factory.createTestData(getScope(), StandardFactory.API_TYPE);
        DataObject child3 = factory.createTestData(getScope(), StandardFactory.API_TYPE);

        List addList = new ArrayList();
        List returnedList;

        addList.add(child1);

        root.setList("containMany", addList);

        // Verify the pre-condition. The List initially has a size of 1.
        assertEquals("The List returned by getList was not of the expected size.", 1, root.getList("containMany").size());

        returnedList = root.getList("containMany");

        /**
         * Add a member to the returned List and verify that it is reflected in
         * the DataObject.
         */

        returnedList.add(child2);

        assertEquals("Update to returned List did not affect DataObject correctly.  Size of children is not 2",
            2, root.getList("containMany").size());
        assertEquals("Update to returned List did not affect DataObject correctly.  child1's container is not equal to root",
            root, child1.getContainer());
        assertEquals("Update to returned List did not affect DataObject correctly.  child2's container is not equal to root",
            root, child2.getContainer());

        /**
         * Delete a child and verify that the returned List is automatically
         * affected.
         */

        child1.delete();
        assertEquals("Deleting a DataObject did not affect the returned List.", 1, returnedList.size());

        /**
         * Verify that the DataObject delete did not affect the original List
         * used in the DataObject.setList().
         */

        assertEquals("Deleting a DataObject should not affect a List unassociated with the DataObject.",
            1,         
            addList.size());

        /**
         * Call DataObject.setList() and verify that the previously returned
         * List reflects the new List.
         */

        addList.add(child2);
        addList.add(child3);
        root.setList("containMany", addList);

        assertEquals("The List returned by DataObject.getList() was not affected by a subsequent DataObject.setList().",
                     3,
                     returnedList.size());
        /**
         * Call List.remove() on the returned List and verify that the
         * DataObject is affected.
         */

        DataObject child = (DataObject)returnedList.get(1);

        // Verify the precondition. The child should have root as its container.
        assertEquals("List.setList() did not cause the expected containment relationship.", root, child.getContainer());

        returnedList.remove(1);

        assertEquals("List.remove() did not have the expected effect on the DataObject.  There are more than 2 children",
                     2, root.getList("containMany").size());
        assertNull("List.remove() did not have the expected effect on the DataObject. child container is not null",
                   child.getContainer());

        /**
         * Call List.clear() and veirfy that the DataObject is affected.
         */
        returnedList.clear();

        assertEquals("List.clear() on the returned List did not have the expected effect on the DataObject. The size of the list of children is not 0",
                     0,root.getList("containMany").size());
        assertNull("List.clear() on the returned List did not have the expected effect on the DataObject.  child1.getContainer is not null",
                   child1.getContainer());
        assertNull("List.clear() on the returned List did not have the expected effect on the DataObject.  child2.getContainer is not null",
                   child2.getContainer());

    }

    /**
     * testActiveUpdatingSequence verifies that updates made to a Sequence
     * returned from a DataObject are reflected in the DataObject and vice
     * versa.
     * @throws Exception 
     */
    @Test
    public void testActiveUpdatingSequence() throws Exception {

    	DataObject sequenceDO = factory.createTestData(getScope(), StandardFactory.SEQ_TYPE);
        Sequence sequence = sequenceDO.getSequence();
        List letterList = sequenceDO.getList("Letters");
        List numberList = sequenceDO.getList("Numbers");

        assertTrue("The Type of sequencedElem is not sequenced.  testActiveUpdatingSequence may not proceed",
                   sequenceDO.getType().isSequenced());

        letterList.clear();
        numberList.clear();

        // Verify the precondition. The Sequence should be empty.
        assertEquals("The Sequence should initially be empty.", 0, sequence.size());

        /**
         * Add values to the DataObject and verify that the Sequence is
         * affected.
         */

        letterList.add("A");
        letterList.add("B");
        numberList.add(Integer.valueOf(8));

        // The expected arrangement of sequence is as follows
        // {<Letters, "A">, <Letters, "B">, <Numbers, 8>}

        assertEquals("Adding values to the DataObject did not affect the returned Sequence.  Sequence size is not 3",
                     3, sequence.size());
        assertEquals("Adding values to the DataObject did not affect the returned Sequence.  getValue[0] is not A",
                     "A", sequence.getValue(0));
        assertEquals("Adding values to the DataObject did not affect the returned Sequence. getValue[1] is not B",
                     "B", sequence.getValue(1)
                     );
        assertEquals("Adding values to the DataObject did not affect the returned Sequence. getValue[2] is not equal to 8",
                     sequence.getValue(2),
                     Integer.valueOf(8));

        /**
         * Remove a value from the DataObject and verify that the Sequence is
         * affected.
         */

        letterList.remove(1);

        // The expected arrangement of sequence is as follows: {<Letters, "A">,
        // <Numbers, 8>}
        assertEquals("Removing a value from the DataObject did not affect the returned Sequence.", sequence.size(), 2);
        assertEquals("Removing a value from the DataObject did not affect the returned Sequence.",
                        "A", sequence.getValue(0)
                     );
        assertEquals("Removing a value from the DataObject did not affect the returned Sequence.",
                     Integer.valueOf(8),
                     sequence.getValue(1));

        /**
         * Remove a value from the Sequence and verify that the DataObject is
         * affected.
         */

        sequence.remove(1);

        // The expected arrangement of sequence is as follows: {<Letters, "A">}

        assertEquals("Removing a value from the Sequence did not affect the DataObject.  Size of List for numbers is not 0",
                     0, sequenceDO.getList("Numbers").size());

        /**
         * Add a value to the Sequence and verify that the DataObject is
         * affected.
         */
        sequence.add("Numbers", Integer.valueOf(16));

        // The expected arrangement of sequence is as follows: {<Letters, "A">,
        // <Numbers, 16>}

        assertEquals("Adding a value to the Sequence did not have the expected effect on the DataObject.", sequenceDO
            .getList("Numbers").size(), 1);
        assertEquals("Adding a value to the Sequence did not have the expected effect on the DataObject.", sequenceDO
            .getList("Numbers").get(0), Integer.valueOf(16));

        // Add several values to the Sequence (via the DataObject) to make
        // Sequence.move() meaningful.

        letterList.add("C");
        numberList.add(Integer.valueOf(15));
        numberList.add(Integer.valueOf(4));
        letterList.add("K");
        letterList.add("M");
        numberList.add(Integer.valueOf(-10));

        // The expected arrangement of sequence is as follows
        // {<Letters, "A">, <Numbers, 16>, <Letters, "C">, <Numbers, 15>,
        // <Numbers, 4>, <Letters, "K">, <Letters, "M">, <Numbers, -10>}

        /**
         * Use Sequence.move() and verify that the changes are reflected in the
         * DataObject.
         */

        sequence.move(1, 5);
        sequence.move(4, 2);

        // The expected arrangement of sequence is as follows
        // {<Letters, "A">, <Letters, "K">, <Letters, "C">, <Numbers, 15>,
        // <Numbers, 16>, <Numbers, 4>, <Letters, "M">, <Numbers, -10>}

        assertEquals("Sequence.move() did not have the expected effect on the DataObject represented by the Sequence.",
                     4,
                     letterList.size());
        assertEquals("Sequence.move() did not have the expected effect on the DataObject represented by the Sequence.",
                     "A",
                     letterList.get(0));
        assertEquals("Sequence.move() did not have the expected effect on the DataObject represented by the Sequence.",
                     "K",
                     letterList.get(1));
        assertEquals("Sequence.move() did not have the expected effect on the DataObject represented by the Sequence.",
                     "C",
                     letterList.get(2));
        assertEquals("Sequence.move() did not have the expected effect on the DataObject represented by the Sequence.",
                     "M",
                     letterList.get(3));

        assertEquals("Sequence.move() did not have the expected effect on the DataObject represented by the Sequence.",
                     4,
                     numberList.size());
        assertEquals("Sequence.move() did not have the expected effect on the DataObject represented by the Sequence.",
                     Integer.valueOf(15),
                     numberList.get(0));
        assertEquals("Sequence.move() did not have the expected effect on the DataObject represented by the Sequence.",
                     Integer.valueOf(16),
                     numberList.get(1));
        assertEquals("Sequence.move() did not have the expected effect on the DataObject represented by the Sequence.",
                     Integer.valueOf(4),
                     numberList.get(2));
        assertEquals("Sequence.move() did not have the expected effect on the DataObject represented by the Sequence.",
                     Integer.valueOf(-10),
                     numberList.get(3));

        // TODO: Add a value to a specific location within the Sequence and
        // veirfy the effect on the DataObject. Awaiting Tuscany-931
    }
    
    /**
     * Verfies that the Property being tested throughout these tests is a
     * contaiment Property
     */
    @Test
    public void verifyIsContainment() {
        Property containmentProp = testDO.getInstanceProperty("containMany");
        assertTrue("Property.isContainment() returned an unexpected value.", containmentProp.isContainment());
    }

    /**
     * Verifies that the initial state after clearContainer is a state in which
     * the DataObject does not have a container.
     */
    @Test
    public void verifyNullContainer() {
        assertNull("DataObject.getContainer() returned an unexpected value.", testDO.getContainer());
    }

    /**
     * Verfiies that the containerless DataObject returns null for
     * getContainmentProperty
     */
    @Test
    public void verifyNullContainmentProperty() {
        assertNull("DataObject.getContainmentProprety() returned an unexpected value.", testDO.getContainmentProperty());
    }

    /**
     * Assign both dataObj1 and dataObj2 to testDO container, then verify
     * DataObject.getContainer() for dataObj1 and dataObj2
     */
    @Test
    public void verifyGetContainer() {
        List addList = new ArrayList();
        Type type = testDO.getType();
        Property containmentProp = testDO.getInstanceProperty("containMany");

        DataObject dataObj1 = getScope().getDataFactory().create(type);
        DataObject dataObj2 = getScope().getDataFactory().create(type);

        // Ensure that any previous containment relationships are broken.

        addList.clear();
        testDO.setList("containMany", addList);
        testDO.detach();
        addList.clear();

        addList.add(dataObj1);
        addList.add(dataObj2);
        testDO.setList(containmentProp, addList);

        // Verify containment of dataObj1 and dataObj2 by testDO

        assertEquals("DataObject.getContainer() did not return the appropriate DataObject.", testDO, dataObj1
            .getContainer());

        assertEquals("DataObject.getContainer() did not return the appropriate DataObject.", testDO, dataObj2
            .getContainer());
    }

    /**
     * Assign both dataObj1 and dataObj2 to testDO container, then verify
     * DataObject.getContainmentProperty for dataObj1 and dataObj2
     */
    @Test
    public void verifyGetContainmentProperty() {
        Property containmentProp = testDO.getInstanceProperty("containMany");
        List addList = new ArrayList();
        Type type = testDO.getType();
        DataObject dataObj1 = getScope().getDataFactory().create(type);
        DataObject dataObj2 = getScope().getDataFactory().create(type);

        addList.add(dataObj1);
        addList.add(dataObj2);
        testDO.setList(containmentProp, addList);

        assertEquals("DataObject.getContainmentProperty() did not return the appropriate Property.",
                     containmentProp,
                     dataObj1.getContainmentProperty());

        assertEquals("DataObject.getContainmentProperty() did not return the appropriate Property.",
                     containmentProp,
                     dataObj2.getContainmentProperty());
    }

    /**
     * Assign both dataObj1 and dataObj2 to testDO container, then verify the
     * contents of the containing property in testDO
     */
    @Test
    public void verifyContainmentContents() {
        assertNull("testDO container !=  null", testDO.getContainer());
        assertEquals("testDO.containMany != 0", 0, testDO.getList("containMany").size());

        Property containmentProp = testDO.getInstanceProperty("containMany");
        List addList = new ArrayList();
        Type type = testDO.getType();
        DataObject dataObj1 = getScope().getDataFactory().create(type);
        DataObject dataObj2 = getScope().getDataFactory().create(type);

        addList.add(dataObj1);
        addList.add(dataObj2);
        testDO.setList(containmentProp, addList);

        List returnedList = testDO.getList(containmentProp);

        assertEquals("DataObject.getList() size is incorrect", 2, returnedList.size());
        assertEquals("DataObject.getList() did not return the List specified in DataObject.setList()",
                     dataObj1,
                     returnedList.get(0));
        assertEquals("DataObject.getList() did not return the List specified in DataObject.setList()",
                     dataObj2,
                     returnedList.get(1));
    }

    /**
     * Assign both dataObj1 and dataObj2 to testDO container, then Assign
     * dataObj2 to dataObj1 container. Verify dataObj2 is automatically removed
     * from testDO container
     */
    @Test
    public void verifyAutomaticRemoval() {
        Property containmentProp = testDO.getInstanceProperty("containMany");
        List addList = new ArrayList();
        Type type = testDO.getType();
        DataObject dataObj1 = getScope().getDataFactory().create(type);
        DataObject dataObj2 = getScope().getDataFactory().create(type);

        addList.add(dataObj1);
        addList.add(dataObj2);
        testDO.setList(containmentProp, addList);

        // Verify the precondition

        assertEquals("DataObject.getContainer() did not return the appropriate DataObject.", testDO, dataObj1
            .getContainer());

        assertEquals("DataObject.getContainer() did not return the appropriate DataObject.", testDO, dataObj2
            .getContainer());

        // After the following section, it should be true that: testDO contains
        // dataObj1 contains dataObj2

        addList.clear();
        addList.add(dataObj2);
        dataObj1.setList(containmentProp, addList);

        // Verify automatic removal of dataObj2 from testDO container

        List returnedList = testDO.getList(containmentProp);
        assertEquals("Once placed in a new container, the DataObject should no longer appear in the former container.",
                     1,
                     returnedList.size());
        assertEquals("Once placed in a new container, the DataObject should no longer appear in the former container.",
                     dataObj1,
                     returnedList.get(0));
    }

    /**
     * Assign both dataObj1 and dataObj2 to testDO container, then Assign
     * dataObj2 to dataObj1 container. Verify dataObj2 is contained by dataObj1
     */
    @Test
    public void verifyNewContainer() {
        Property containmentProp = testDO.getInstanceProperty("containMany");
        List addList = new ArrayList();
        Type type = testDO.getType();
        DataObject dataObj1 = getScope().getDataFactory().create(type);
        DataObject dataObj2 = getScope().getDataFactory().create(type);

        addList.add(dataObj1);
        addList.add(dataObj2);
        testDO.setList(containmentProp, addList);

        // After the following section, it should be true that: testDO contains
        // dataObj1 contains dataObj2

        addList.clear();
        addList.add(dataObj2);
        dataObj1.setList(containmentProp, addList);

        // Verify that dataObj2 was correctly added to dataObj1 container

        List returnedList = dataObj1.getList(containmentProp);
        assertEquals("Once assigned to a new container, the DataObject should appear in the new container.",
                     1,
                     returnedList.size());
        assertEquals("Once assigned to a new container, the DataObject should appear in the new container.",
                     dataObj2,
                     returnedList.get(0));
        assertEquals("DataObject.getContainer() did not return the appropriate DataObject.", dataObj1, dataObj2
            .getContainer());
    }

    /**
     * Verify that detach() removes the object from its container.
     */
    @Test
    public void verifyDetachRemoval() {
        Property containmentProp = testDO.getInstanceProperty("containMany");
        List addList = new ArrayList();
        Type type = testDO.getType();
        DataObject dataObj1 = getScope().getDataFactory().create(type);
        DataObject dataObj2 = getScope().getDataFactory().create(type);

        // After the following section, it should be true that: dataObj1
        // contains testDO contains dataObj2

        addList.add(dataObj2);
        testDO.setList(containmentProp, addList);
        addList.clear();
        addList.add(testDO);
        dataObj1.setList(containmentProp, addList);

        testDO.detach();

        List returnedList = dataObj1.getList(containmentProp);
        assertEquals("Detaching the contained object did not remove it from container", 0, returnedList.size());

        assertNull("DataObject.getContainer() did not return null as expected for a detached DataObject.", testDO
            .getContainer());
    }

    /**
     * Verify that DataObject.detach() does not affect objects contained by the
     * detached DataObject
     */
    @Test
    public void verifyDetachContainer() {
        Property containmentProp = testDO.getInstanceProperty("containMany");
        List addList = new ArrayList();
        Type type = testDO.getType();
        DataObject dataObj1 = getScope().getDataFactory().create(type);
        DataObject dataObj2 = getScope().getDataFactory().create(type);

        // After the following section, it should be true that: dataObj1
        // contains testDO contains dataObj2

        addList.add(testDO);
        dataObj1.setList(containmentProp, addList);
        addList.clear();
        addList.add(dataObj2);
        testDO.setList(containmentProp, addList);

        testDO.detach();

        List returnedList = testDO.getList(containmentProp);

        assertEquals("Detaching a DataObject should not detach its contained DataObjects.", 1, returnedList.size());
        assertEquals("Detaching a DataObject should not affect it as a container.", dataObj2, returnedList.get(0));
    }

    /**
     * Verify that DataObject.detach() does not affect objects contained by the
     * detached DataObject
     */
    @Test
    public void verifyDetachContainedDOs() {
        Property containmentProp = testDO.getInstanceProperty("containMany");
        List addList = new ArrayList();
        Type type = testDO.getType();
        DataObject dataObj1 = getScope().getDataFactory().create(type);
        DataObject dataObj2 = getScope().getDataFactory().create(type);

        // After the following section, it should be true that: dataObj1
        // contains testDO contains dataObj2

        addList.add(testDO);
        dataObj1.setList(containmentProp, addList);
        addList.clear();
        addList.add(dataObj2);
        testDO.setList(containmentProp, addList);

        testDO.detach();

        assertEquals("Detaching a DataObject should not affect contained DataObjects.", testDO, dataObj2.getContainer());
    }

    /**
     * Verify that DataObject.delete() removes the object from its container.
     */
    @Test
    public void verifyDeleteRemoval() {
        Property containmentProp = testDO.getInstanceProperty("containMany");
        List addList = new ArrayList();
        Type type = testDO.getType();
        DataObject dataObj1 = getScope().getDataFactory().create(type);
        DataObject dataObj2 = getScope().getDataFactory().create(type);

        // After the following section, it should be true that: dataObj1
        // contains testDO contains dataObj2

        addList.add(testDO);
        dataObj1.setList(containmentProp, addList);
        addList.clear();
        addList.add(dataObj2);
        testDO.setList(containmentProp, addList);

        testDO.delete();

        assertEquals("Deleting the DataObject did not remove it from its container.", 0, dataObj1
            .getList(containmentProp).size());
    }

    /**
     * Verify that DataObject.delete() removes the containment reflected by the
     * deleted DataObject
     */
    @Test
    public void verifyDeleteResultsOnDeleted() {
        Property containmentProp = testDO.getInstanceProperty("containMany");
        List addList = new ArrayList();
        Type type = testDO.getType();
        DataObject dataObj1 = getScope().getDataFactory().create(type);
        DataObject dataObj2 = getScope().getDataFactory().create(type);

        // After the following section, it should be true that: dataObj1
        // contains testDO contains dataObj2

        addList.add(testDO);
        dataObj1.setList(containmentProp, addList);
        addList.clear();
        addList.add(dataObj2);
        testDO.setList(containmentProp, addList);

        testDO.delete();

        assertNotNull("A deleted DataObject should remain programatically accessible.", testDO);
        assertNull("Deleting the DataObject did not affect its view of its container.", testDO.getContainer());
    }

    /**
     * Verify that DataObject.delete() removes its contents as a container.
     */
    @Test
    public void verifyDeleteAsContainer() {
        Property containmentProp = testDO.getInstanceProperty("containMany");
        List addList = new ArrayList();
        Type type = testDO.getType();
        DataObject dataObj1 = getScope().getDataFactory().create(type);
        DataObject dataObj2 = getScope().getDataFactory().create(type);

        // After the following section, it should be true that: dataObj1
        // contains testDO contains dataObj2

        addList.add(testDO);
        dataObj1.setList(containmentProp, addList);
        addList.clear();
        addList.add(dataObj2);
        testDO.setList(containmentProp, addList);

        testDO.delete();

        assertNotNull("A deleted DataObject should remain programatically accessible.", testDO);
        assertEquals("Deleting the DataObject did not empty it as a container.", 0, testDO.getList(containmentProp)
            .size());
    }

    /**
     * Verify that DataObject.delete() affects contained DataObjects.
     */
    @Test
    public void verifyDeleteAffectOnContained() {
        Property containmentProp = testDO.getInstanceProperty("containMany");
        List addList = new ArrayList();
        Type type = testDO.getType();
        DataObject dataObj1 = getScope().getDataFactory().create(type);
        DataObject dataObj2 = getScope().getDataFactory().create(type);

        // After the following section, it should be true that: dataObj1
        // contains testDO contains dataObj2

        addList.add(testDO);
        dataObj1.setList(containmentProp, addList);
        addList.clear();
        addList.add(dataObj2);
        testDO.setList(containmentProp, addList);

        testDO.delete();

        assertNull("Deleting the containing DataObject was not reflected in the contained DataObject.", dataObj2
            .getContainer());
    }
    
    /**
     * testRecursiveDeletion verifies that when a DataObject is deleted, all
     * (recursively) contained DataObjects are also deleted.
     */
    @Test
    public void testRecursiveDeletion() {
        Type type = testDO.getType();
        Property containmentProp = type.getProperty("containMany");

        assertTrue("Cannot continue with test because Property.isContainment() is false.", containmentProp
            .isContainment());

        DataFactory df = getScope().getDataFactory();
        DataObject child1 = df.create(type);
        DataObject child2 = df.create(type);
        DataObject child3 = df.create(type);

        List addList = new ArrayList();

        /**
         * Establish a series of containment relationships
         */

        addList.add(child1);
        testDO.setList(containmentProp, addList);

        addList.clear();
        addList.add(child2);
        child1.setList(containmentProp, addList);

        addList.clear();
        addList.add(child3);
        child2.setList(containmentProp, addList);

        /**
         * Verify that containment has been established correctly.
         */

        assertEquals("The expected containment relationships were not correctly formed.", child3.getContainer(), child2);
        assertEquals("The expected containment relationships were not correctly formed.", child2.getContainer(), child1);
        assertEquals("The expected containment relationships were not correctly formed.", child1.getContainer(), testDO);

        /**
         * Delete the root DataObject and verify that contained DataObjects are
         * recursively affected.
         */

        testDO.delete();

        assertEquals("DataObject.delete() did not recursively affect contained DataObjects.", testDO
            .getList(containmentProp).size(), 0);
        assertNull("DataObject.delete() did not recursively affect contained DataObjects.", child1.getContainer());
        assertNull("DataObject.delete() did not recursively affect contained DataObjects.", child2.getContainer());
        assertNull("DataObject.delete() did not recursively affect contained DataObjects.", child3.getContainer());

    }
}
