/**
 *  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.general;

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 static org.junit.Assert.fail;

import java.io.IOException;
import java.io.Reader;
import java.net.URL;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Vector;

//import org.junit.Before;
import javax.xml.namespace.QName;
import javax.xml.transform.stream.StreamSource;

import org.apache.ws.commons.schema.XmlSchema;
import org.apache.ws.commons.schema.XmlSchemaCollection;
import org.apache.ws.commons.schema.XmlSchemaComplexType;
import org.apache.ws.commons.schema.XmlSchemaObject;
import org.apache.ws.commons.schema.XmlSchemaObjectTable;
import org.apache.ws.commons.schema.XmlSchemaType;
import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.Ignore;

import test.sdo21.CTSSuite;
import test.sdo21.framework.CTSTestCase;

import commonj.sdo.DataObject;
import commonj.sdo.Type;
import commonj.sdo.helper.HelperContext;
import commonj.sdo.helper.TypeHelper;
import commonj.sdo.helper.XSDHelper;

/**
 * Tests XSD serialization/deserialization.<p/>
 * This tests requires extension by import or creation of further tests.
 * It currently only tests one flavour of {@link XSDHelper#define(java.io.InputStream, String)} and {@link XSDHelper#generate(List)})
 * 
 * @see <a href="http://osoa.org/download/attachments/36/Java-SDO-Spec-v2.1.0-FINAL.pdf?version=1#page=52">2.1 spec section 3.13</a>
 * @see <a href="http://osoa.org/download/attachments/36/Java-SDO-Spec-v2.1.0-FINAL.pdf?version=1#page=56">2.1 spec section 4</a>
 * 
 */
public class XSDHelperTest extends CTSTestCase {
    private static final String TEST_MODEL = "/simple.xsd";
    private XmlSchemaCollection col = new XmlSchemaCollection();
    private static URL modelURL;

    /**
     * Obtains test model resource. Runs once before any of the test methods.
     */
    @BeforeClass
    public static void obtainResource() {
        modelURL = XSDHelperTest.class.getResource(TEST_MODEL);
    }
    
    @Before public void setUp() throws Exception
    {
      super.setUp();
    }
    
    @After
    public void tearDown() throws Exception {
      super.tearDown();
    }

    /**
     * Verifies the performance of XSDHelper.define() when a SchemaLocation is provided.
     * @see <a href="http://osoa.org/download/attachments/36/Java-SDO-Spec-v2.1.0-FINAL.pdf?version=1#page=52">2.1 spec section 3.13</a>
     * @see commonj.sdo.XSDHelper#define(InputStream, String)
     */
    @Test
    public void testDefineWithLocation() {
        try {

            XSDHelper xsdHelper = getScope().getXSDHelper();
            List types = xsdHelper.define(modelURL.openStream(), modelURL.toString());
            checkTypes(modelURL, getScope().getTypeHelper(), types);
         } catch (Exception e) {
            fail("Exception calling xsdHelper.define" + e.toString());
        }
    }

    
    /**
     * Utility method to ensure that the set of types in the list includes all those explicity
     * defined in the schema<p>
     * Checking xsd type definition post condition ---<br/>
     * <i>for all t in schemaTypes there exists a t' in types such that QName(t) == QName(t')</i>
     * @param modelUrl location of the schema related to the set of types
     * @param typeHelper associated with the scope for the types in the list
     * @param types
     */
    private void checkTypes(URL modelUrl, TypeHelper typeHelper, List types) {
      try {
          XmlSchema schema = col.read(new StreamSource(modelUrl.openStream()), null);
          XmlSchemaObjectTable schemaTypes = schema.getSchemaTypes();
          
          Iterator<XmlSchemaType> it = schemaTypes.getValues();
          XmlSchemaType schemaType;
          while (it.hasNext()){
              schemaType = it.next();
              QName qname = schemaType.getQName();
              Type sdoType = typeHelper.getType(qname.getNamespaceURI(), qname.getLocalPart());
              assertNotNull("Type not known to SDO environment: "+ qname, sdoType);
              assertTrue("Sdo type not created from this invocation of type definition", types.contains(sdoType));
          }
      } catch (IOException e) {

          fail("Exception parsing schema" + e);
      }
  }

    /**
     * Verifies the performance of XSDHelper.define() when a SchemaLocation is not provided.
     * @see <a href="http://osoa.org/download/attachments/36/Java-SDO-Spec-v2.1.0-FINAL.pdf?version=1#page=52">2.1 spec section 3.13</a>
     * @see commonj.sdo.XSDHelper#define(InputStream, String)
     */
    @Test
    public void testDefineWithNoLocation() {
        try {
            XSDHelper xsdHelper = getScope().getXSDHelper();
            List types = xsdHelper.define(XSDHelperTest.class.getResourceAsStream(TEST_MODEL), null);
            checkTypes(modelURL, getScope().getTypeHelper(), types);
            //assertEquals("XSDHelper.define() did not create the expected number of Types", 2, types.size());

        } catch (Exception e) {
            e.printStackTrace();
            fail("Exception caught" + e.toString());
        }
    }

    /**
     * Verifies that duplicate Types are not redefined.
     * @see <a href="http://osoa.org/download/attachments/36/Java-SDO-Spec-v2.1.0-FINAL.pdf?version=1#page=52">2.1 spec section 3.13</a>
     * @see commonj.sdo.XSDHelper#define(InputStream, String)
     */
    @Test
    public void testDuplicateDefineWithLocation() {
        try {
            XSDHelper xsdHelper = getScope().getXSDHelper();
            List types = xsdHelper.define(modelURL.openStream(), modelURL.toString());
            assertTrue("XSDHelper.define() did not create the expected number of Types", types.size() > 0);
            // redefine type
            List duplicateTypes = xsdHelper.define(modelURL.openStream(), modelURL.toString());
            assertEquals("XSDHelper.define() did not create the expected number of Types", 0, duplicateTypes.size());

        } catch (Exception e) {
            e.printStackTrace();
            fail("Exception caught" + e.toString());
        }
    }

    /**
     * Verifies the performance of XSDHelper.generate for dynamic SDOs with no XSD model.<p/>
     * Could improve this by postconditions on generated schema. 
     * @see commonj.sdo.XSDHelper#generate(InputStream, String)
     * @see <a href="http://osoa.org/download/attachments/36/Java-SDO-Spec-v2.1.0-FINAL.pdf?version=1#page=53">2.1 spec section 3.13.2</a>
     * @see <a href="http://osoa.org/download/attachments/36/Java-SDO-Spec-v2.1.0-FINAL.pdf?version=1#page=56">2.1 spec section 4</a>
     */
    @Test
    public void testXSDGeneration_DynamicSDOType() {
        try {
            boolean exceptionCaught = false;

            // test for dynamic SDOs that have no XSD model. Here the testcase
            // succeeds only if the
            // xsd is generated by XSDHelper in which case xsd must not be null
            XSDHelper xsdHelper = getScope().getXSDHelper();
            DataObject quoteType = getScope().getDataFactory().create("commonj.sdo", "Type");
            quoteType.set("uri", "http://www.example.com/dynamic");
            quoteType.set("name", "DynamicQuote");

            TypeHelper th = getScope().getTypeHelper();
            DataObject aProperty = quoteType.createDataObject("property");
            aProperty.set("name", "symbol");
            aProperty.set("type", th.getType("commonj.sdo", "String"));

            aProperty = quoteType.createDataObject("property");
            aProperty.set("name", "price");
            aProperty.set("type", th.getType("commonj.sdo", "Decimal"));

            aProperty = quoteType.createDataObject("property");
            aProperty.set("name", "volume");
            aProperty.set("type", th.getType("commonj.sdo", "Double"));

            th.define(quoteType);

            Type dynamicQuoteType = th.getType("http://www.example.com/dynamic", "DynamicQuote");

            Vector types = new Vector();
            types.add(dynamicQuoteType);
            String xsd = null;

            try {
                xsd = xsdHelper.generate(types);
                assertNotNull("XSDHelper.generate() did not complete as expected for dynamic SDOs with no XSD model.  Exception was thrown",
                    xsd);
            } catch (IllegalArgumentException e) {
                fail("XSDHelper.generate() did not complete as expected for dynamic SDOs with no XSD model.  Exception was thrown : " + e
                    .toString());
            } catch (Exception e) {
                fail("Exception caught when generating a schema");
            }

        } catch (Exception e) {
            e.printStackTrace();
            fail("Exception caught" + e.toString());
        }
    }
    
}
