/*
 *  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.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.fail;

import org.junit.After;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;

import test.sdo21.framework.CTSTestCase;
import test.sdo21.tests.util.CTSUtil;

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

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

/**
 * Set of tests for DataObject APIs.
 * Currently limited to a fairly narrow set of tests on the set(Property, value), isSet(), and unSet()
 * methods.
 * <p/>
 * TODO Need to extend the test set or migrate tests from other existing tests as yet unidentified.
 */
public class DataObjectTest extends CTSTestCase  {

    private boolean debug = false;
    private static int uniqueNumber = 1;
    
    @Before
    public void setUp() throws Exception {
      super.setUp();
    }
    
    


    /**
     * This test checks that getInstanceProperties returns all properties
     * defined by the DataObject's type, regardless of whether they are set or
     * not. It also checks that open content properties only appear in
     * getInstanceProperties if they are set. Related sections in the
     * specification are  / 3.1.9 / 3.1.11 Related JIRA SDO-179
     * @see <a href="http://osoa.org/download/attachments/36/Java-SDO-Spec-v2.1.0-FINAL.pdf?version=1#page=14">2.1 spec section 3.1.1</a>
     * @see <a href="http://osoa.org/download/attachments/36/Java-SDO-Spec-v2.1.0-FINAL.pdf?version=1#page=18">2.1 spec section 3.1.9</a>
     * @see <a href="http://osoa.org/download/attachments/36/Java-SDO-Spec-v2.1.0-FINAL.pdf?version=1#page=20">2.1 spec section 3.1.11</a>
     * @see <a href="http://www.xcalia.com/support/browse/SDO-179">SDO Spec JIRA 179</a>
     * @throws Exception
     */
    @Test
    @Ignore("On demand open content property is not yet implemented in Tuscany.")
    public void testGetInstancePropertiesSize() throws Exception {

        // define a type with two properties
    	  HelperContext helperContext = getScope();
        String typeName = getTypeName();
        DataObject typeDef = CTSUtil.createTypeDef("", typeName, true, helperContext);
        CTSUtil.createPropertyDef(typeDef, "p1", "commonj.sdo#String", false, false, helperContext);
        CTSUtil.createPropertyDef(typeDef, "p2", "commonj.sdo#String", false, false, helperContext);
        helperContext.getTypeHelper().define(typeDef);

        // create a DataObject that uses this type
        DataObject dobj = helperContext.getDataFactory().create("", typeName);

        // getInstanceProperties() should return p1, p2 even though they are not
        // set
        // System.out.println(dobj.getInstanceProperties());
        assertEquals(2, dobj.getInstanceProperties().size());

        dobj.set("p1", "foo");

        // getInstanceProperties() should still return p1, p2
        assertEquals(2, dobj.getInstanceProperties().size());

        dobj.unset("p1");

        // getInstanceProperties() should still return p1, p2
        assertEquals(2, dobj.getInstanceProperties().size());

        // set an on-demand open content property
        dobj.set("p3", "foo");

        // getInstanceProperties() should now return p1, p2, p3
        assertEquals(3, dobj.getInstanceProperties().size());

        // unset the on-demand property
        dobj.unset("p3");

        // the spec says that open content properties only appear in
        // getInstancePropeties if
        // they are set so we expect the list to be smaller now
        assertEquals(2, dobj.getInstanceProperties().size());
    }

    /**
     * Tests an isMany=false Boolean type property in an open type for being set to false/unset.
     * @see <a href="http://osoa.org/download/attachments/36/Java-SDO-Spec-v2.1.0-FINAL.pdf?version=1#page=16">2.1 spec section 3.1.5</a>
     * @see commonj.sdo.DataObject#isSet()
     * @see commonj.sdo.DataObject#unset()
     * @see commonj.sdo.DataObject#set(Property, Boolean)
     * @throws Exception
     */
    @Test
    public void testIsSet_Boolean_false() throws Exception {

        // define a type with two properties
    	  HelperContext helperContext = getScope();
        String typeName = getTypeName();
        DataObject typeDef = CTSUtil.createTypeDef("", typeName, true, helperContext);
        CTSUtil.createPropertyDef(typeDef, "b1", "commonj.sdo#Boolean", false, false, helperContext);
        helperContext.getTypeHelper().define(typeDef);

        // create a DataObject that uses this type
        DataObject testDO = helperContext.getDataFactory().create("", typeName);

        Property p = testDO.getInstanceProperty("b1");
        testDO.unset(p);
        assertFalse("Property was set", testDO.isSet(p));
        testDO.set(p, false);
        assertTrue("Property was not set ", testDO.isSet(p));
    }

    /**
     * Tests an isMany=false Boolean type property in an open type for being set to true/unset.
     * @see <a href="http://osoa.org/download/attachments/36/Java-SDO-Spec-v2.1.0-FINAL.pdf?version=1#page=16">2.1 spec section 3.1.5</a>
     * @see commonj.sdo.DataObject#getInstanceProperty(String)
     * @see commonj.sdo.DataObject#isSet()
     * @see commonj.sdo.DataObject#unset()
     * @see commonj.sdo.DataObject#set(Property, Boolean)
     * @throws Exception
     */
    @Test
    public void testIsSet_Boolean_true() throws Exception {

        // define a type with two properties
      	HelperContext helperContext = getScope();
        String typeName = getTypeName();
        DataObject typeDef = CTSUtil.createTypeDef("", typeName, true, helperContext);
        CTSUtil.createPropertyDef(typeDef, "b1", "commonj.sdo#Boolean", false, false, helperContext);
        helperContext.getTypeHelper().define(typeDef);

        // create a DataObject that uses this type
        DataObject testDO = helperContext.getDataFactory().create("", typeName);

        Property p = testDO.getInstanceProperty("b1");
        testDO.unset(p);
        assertFalse("Property was set", testDO.isSet(p));
        testDO.set(p, true);
        assertTrue("Property was not set " + testDO.get(p), testDO
            .isSet(p));
    }

    /**
     * Tests isSet() of Integer property where isMany = false in an open type.
     * @see <a href="http://osoa.org/download/attachments/36/Java-SDO-Spec-v2.1.0-FINAL.pdf?version=1#page=16">2.1 spec section 3.1.5</a>
     * @see commonj.sdo.DataObject#isSet()
     * @see commonj.sdo.DataObject#unset()
     * @see commonj.sdo.DataObject#set(Property, Integer)
     * @throws Exception
     */
    @Test
    public void testIsSet_Integer_0() throws Exception {

        // define a type with two properties
      	HelperContext helperContext = getScope();
        String typeName = getTypeName();
        DataObject typeDef = CTSUtil.createTypeDef("", typeName, true, helperContext);
        CTSUtil.createPropertyDef(typeDef, "i1", "commonj.sdo#Integer", false, false, helperContext);
        helperContext.getTypeHelper().define(typeDef);

        // create a DataObject that uses this type
        DataObject testDO = helperContext.getDataFactory().create("", typeName);

        Property p = testDO.getInstanceProperty("i1");
        testDO.unset(p);
        assertFalse("Property was set", testDO.isSet(p));
        testDO.set(p, java.math.BigInteger.valueOf(0));
        assertTrue("Property was not set" + testDO.get(p), testDO.isSet(p));
    }

    /**
     * Ensures correct behaviour (returns null) on attempting to get a non existent property in an open type.<br/>
     * Tests isSet() after unset() and set() on isMany=false property
     * @see commonj.sdo.DataObject#getInstanceProperty(String)
     * @see commonj.sdo.DataObject#isSet()
     * @see commonj.sdo.DataObject#unset()
     * @see commonj.sdo.DataObject#set(Property, Integer)
     * @see <a href="http://osoa.org/download/attachments/36/Java-SDO-Spec-v2.1.0-FINAL.pdf?version=1#page=16">2.1 spec section 3.1.5</a>
     * @throws Exception
     */
    @Test
    public void testIsSet_Integer_1() throws Exception {

      	HelperContext helperContext = getScope();
        String typeName = getTypeName();
        DataObject typeDef = CTSUtil.createTypeDef("", typeName, true, helperContext);
        CTSUtil.createPropertyDef(typeDef, "i1", "commonj.sdo#Integer", false, false, helperContext);
        helperContext.getTypeHelper().define(typeDef);

        // create a DataObject that uses this type
        DataObject testDO = helperContext.getDataFactory().create("", typeName);
        try {
            Property p = testDO.getInstanceProperty("default");
            assertTrue("non null return for non-existent property in an open type", p==null);
        } catch (Exception e) {
            assertTrue("getInstanceProperty throws exception for non-existent property "+e, false);
        }

        Property p = testDO.getInstanceProperty("i1");
        testDO.unset(p);
        assertFalse("Property was set ", testDO.isSet(p));

        testDO.set(p, java.math.BigInteger.valueOf(1));
        assertTrue("Property was not set  ", testDO.isSet(p));
    }

    /**
     * Tests isSet() after unset() and set() on isMany=false property of type Int in an open type
     * @see commonj.sdo.DataObject#getInstanceProperty(String)
     * @see commonj.sdo.DataObject#isSet()
     * @see commonj.sdo.DataObject#unset()
     * @see commonj.sdo.DataObject#set(Property, Integer)
     * @see <a href="http://osoa.org/download/attachments/36/Java-SDO-Spec-v2.1.0-FINAL.pdf?version=1#page=16">2.1 spec section 3.1.5</a>
     * @throws Exception
     */
    @Test
    public void testIsSet_int_1() throws Exception {

      	HelperContext helperContext = getScope();
        String typeName = getTypeName();
        DataObject typeDef = CTSUtil.createTypeDef("", typeName, true, helperContext);
        Type intType = helperContext.getTypeHelper().getType("commonj.sdo", "Int");

        CTSUtil.createPropertyDef(typeDef, "i1", intType, false, false);
        helperContext.getTypeHelper().define(typeDef);

        // create a DataObject that uses this type
        DataObject testDO = helperContext.getDataFactory().create("", typeName);

        Property p = testDO.getInstanceProperty("i1");
        testDO.unset(p);
        assertFalse("Property was not unset", testDO.isSet(p));

        testDO.set(p, 1);
        assertTrue("Property was not set " , testDO.isSet(p));
    }

    /**
     * Tests an open type
     * @throws Exception
     */
    @Test
    public void testIsSet_int_0() throws Exception {
        try {

          	HelperContext helperContext = getScope();
            String typeName = getTypeName();
            DataObject typeDef = CTSUtil.createTypeDef("", typeName, true, helperContext);
            Type intType = helperContext.getTypeHelper().getType("commonj.sdo", "Int");
            CTSUtil.createPropertyDef(typeDef, "i1", intType, false, false);
            helperContext.getTypeHelper().define(typeDef);

            // create a DataObject that uses this type
            DataObject testDO = helperContext.getDataFactory().create("", typeName);

            Property p = testDO.getInstanceProperty("i1");
            testDO.unset(p);
            assertFalse("Property was set", testDO.isSet(p));

            testDO.set(p, 0);
            if (debug) {
                helperContext.getXMLHelper().save(testDO, "http://www.example.com/api_test", "apiTestElem", System.out);
            }
            assertTrue("Property was not set", testDO.isSet(p));

        } catch (Exception e) {
            assertFalse("No exception expected: received " + e.toString(), true);
        }
    }

    @Test
    public void testOpenTypeBadPropertyReturnsDefault() {
        // define an open type with no properties
        HelperContext helperContext = getScope();
        String typeName = getTypeName();
        DataObject typeDef = CTSUtil.createTypeDef("", typeName, true, helperContext);
        helperContext.getTypeHelper().define(typeDef);

        // create a DataObject that uses this type
        DataObject testDO = helperContext.getDataFactory().create("", typeName);

        // get() should not throw an exception but return an appropriate default value
        assertEquals( null, testDO.get( "foo" ) );
        assertEquals( null, testDO.getDataObject( "foo" ) );
        assertEquals( null, testDO.getList( "foo" ) );
        assertEquals( null, testDO.getString( "foo" ) );
        assertEquals( null, testDO.getBigDecimal( "foo" ) );
        assertEquals( null, testDO.getBigInteger( "foo" ) );
        assertEquals( null, testDO.getDate( "foo" ) );
        assertEquals( null, testDO.getBytes( "foo" ) );
        assertEquals( (byte) 0, testDO.getByte( "foo" ) );
        assertEquals( (short) 0, testDO.getShort( "foo" ) );
        assertEquals( (int) 0, testDO.getInt( "foo" ) );
        assertEquals( (long) 0, testDO.getLong( "foo" ) );
        assertEquals( (double) 0, testDO.getDouble( "foo" ) );
        assertEquals( (float) 0, testDO.getFloat( "foo" ) );
    }

    /**
     * Test that getList() returns null for an unset open content property.
     *
     */
    @Test
    public void testGetList() {

        // define an open type with no properties
        HelperContext helperContext = getScope();
        String typeName = getTypeName();
        DataObject typeDef = CTSUtil.createTypeDef("", typeName, true, helperContext);
        helperContext.getTypeHelper().define(typeDef);

        // create a DataObject that uses this type
        DataObject testDO = helperContext.getDataFactory().create("", typeName);

        // test that getList() returns null for an unst open content property
        assertNull( testDO.getList("foo") );
        testDO.set("foo", new ArrayList());
        assertNotNull( testDO.getList("foo") );
        testDO.unset("foo");
        assertNull( testDO.getList("foo") );
    }

    /**
     * Test that it is possible to add a null value to a List retrieved by calling DataObject.getList()
     *
     */
    @Test
    public void testAddNullToList() {
        HelperContext helperContext = getScope();
        XMLDocument doc = helperContext.getXMLHelper().load("<catalog2><product2/><product2/></catalog2>");
        List listTest = doc.getRootObject().getList("product2");
        assertNotNull(listTest);
        assertEquals(2, listTest.size());
        listTest.add( null );
        assertEquals(3, listTest.size());
        String xml = helperContext.getXMLHelper().save( doc.getRootObject(), doc.getRootElementURI(), doc.getRootElementName() );
        assertTrue( xml.indexOf("xsi:nil=\"true\"") > 0 );

    }

    /**
     * Creates a unique type name for each test so that the types won't clash if an implementation
     * provides its default HelperContext when running the tests.
     * 
     * @return
     */
    private String getTypeName() {
      return "DataObjectTestType" + (++uniqueNumber);
    }

    @Override
    @After
    public void tearDown() throws Exception {
      super.tearDown();
    }
}
