/*
 * 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 org.apache.commons.chain2.config.xml;

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

import java.net.URL;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.chain2.Catalog;
import org.apache.commons.chain2.CatalogFactory;
import org.apache.commons.chain2.Context;
import org.apache.commons.chain2.Processing;
import org.apache.commons.chain2.impl.CatalogBase;
import org.apache.commons.chain2.impl.CatalogFactoryBase;
import org.apache.commons.chain2.impl.ContextBase;
import org.apache.commons.chain2.testutils.HasCommandCount;
import org.apache.commons.chain2.testutils.HasLog;
import org.apache.commons.digester3.Digester;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;

/**
 * Parameterized test case for {@link XmlConfigParser}, that uses config locations as data points.
 *
 * <p><strong>Note:</strong> This test case assumes,
 * that all config files will be parsed to the same catalog
 * and command instances.</p>
 *
 * @version $Id$
 */
@RunWith(Parameterized.class)
public class XmlConfigParserTestCase {

    /** Catalog */
    private Catalog<String, Object, Context<String, Object>> catalog = null;
    /** Context */
    private Context<String, Object> context = null;
    /** XmlConfigParser */
    private XmlConfigParser parser = null;
    /** configLocation */
    private final String configLocation;

    /**
     * @param location String
     */
    public XmlConfigParserTestCase(final String location) {
        this.configLocation = location;
    }

    /**
     * @return List
     */
    @Parameterized.Parameters
    public static List<Object[]> data() {
        return Arrays.asList(new Object[][]
            {
                {"/org/apache/commons/chain2/config/xml/test-config.xml"},
                {"/org/apache/commons/chain2/config/xml/test-config-2.xml"}
            }
        );
    }

    /**
     * Setup
     */
    @Before
    public void setUp() {
        init();
        load(this.configLocation);
    }

    /**
     * init
     */
    private void init() {
        CatalogFactoryBase.clear();
        this.catalog = new CatalogBase<>();
        this.context = new ContextBase();
        this.parser = new XmlConfigParser();
    }

    /**
     * Teardown
     */
    @After
    public void tearDown() {
        this.parser = null;
        this.context = null;
        this.catalog = null;
    }

    /**
     * Load the default test-config.xml file and examine the results
     */
    @Test
    public void testDefault() {

        // Check overall command count
        assertThat(this.catalog, HasCommandCount.hasCommandCount(17));

        // Check individual single command instances
        assertNotNull(this.catalog.getCommand("AddingCommand"));

        assertNotNull(this.catalog.getCommand("DelegatingCommand"));

        assertNotNull(this.catalog.getCommand("DelegatingFilter"));

        assertNotNull(this.catalog.getCommand("ExceptionCommand"));

        assertNotNull(this.catalog.getCommand("ExceptionFilter"));

        assertNotNull(this.catalog.getCommand("NonDelegatingCommand"));

        assertNotNull(this.catalog.getCommand("NonDelegatingFilter"));

        Object chain = this.catalog.getCommand("ChainBase");
        assertNotNull(chain);
        assertTrue(chain instanceof TestChain);

        // Check configurable properties instance
        Object command = this.catalog.getCommand("Configurable");
        assertNotNull(command);
        assertEquals(TestCommand.class, command.getClass());
        assertEquals("Foo Value", ((TestCommand)command).getFoo());
        assertEquals("Bar Value", ((TestCommand)command).getBar());

    }

    /**
     * Test execution of chain "Execute2a"
     */
    @Test
    public void testExecute2a() {

        assertEquals(Processing.FINISHED,
                this.catalog.getCommand("Execute2a").execute(this.context));
        assertThat(this.context, HasLog.hasLog("1/2/3"));

    }

    /**
     * Test execution of chain "Execute2b"
     */
    @Test
    public void testExecute2b() {

        assertEquals(Processing.CONTINUE,
                this.catalog.getCommand("Execute2b").execute(this.context));
        assertThat(this.context, HasLog.hasLog("1/2/3"));

    }

    /**
     * Test execution of chain "Execute2c"
     */
    @Test
    public void testExecute2c() {

        try {
            this.catalog.getCommand("Execute2c").execute(this.context);
        } catch (final ArithmeticException e) {
            assertEquals("Correct exception id", "3", e.getMessage());
        }
        assertThat(this.context, HasLog.hasLog("1/2/3"));

    }

    /**
     * Test execution of chain "Execute2d"
     */
    @Test
    public void testExecute2d() {

        try {
            this.catalog.getCommand("Execute2d").execute(this.context);
        } catch (final ArithmeticException e) {
            assertEquals("Correct exception id", "2", e.getMessage());
        }
        assertThat(this.context, HasLog.hasLog("1/2"));

    }

    /**
     * Test execution of chain "Execute4a"
     */
    @Test
    public void testExecute4a() {

        assertEquals(Processing.FINISHED,
                this.catalog.getCommand("Execute4a").execute(this.context));
        assertThat(this.context, HasLog.hasLog("1/2/3/c/a"));

    }

    /**
     * Test execution of chain "Execute2b"
     */
    @Test
    public void testExecute4b() {

        assertEquals(Processing.CONTINUE,
                this.catalog.getCommand("Execute4b").execute(this.context));
        assertThat(this.context, HasLog.hasLog("1/2/3/b"));

    }

    /**
     * Test execution of chain "Execute4c"
     */
    @Test
    public void testExecute4c() {

        try {
            this.catalog.getCommand("Execute4c").execute(this.context);
        } catch (final ArithmeticException e) {
            assertEquals("Correct exception id",
                    "3", e.getMessage());
        }
        assertThat(this.context, HasLog.hasLog("1/2/3/c/b/a"));
    }

    /**
     * Test execution of chain "Execute4d"
     */
    @Test
    public void testExecute4d() {

        try {
            this.catalog.getCommand("Execute4d").execute(this.context);
        } catch (final ArithmeticException e) {
            assertEquals("Correct exception id",
                    "2", e.getMessage());
        }
        assertThat(this.context, HasLog.hasLog("1/2/b/a"));
    }

    /**
     * Test a pristine ConfigParser instance
     */
    @Test
    public void testPristine() {

        init();
        // Validate the "digester" property
        Digester digester = this.parser.getDigester();
        assertNotNull("Returned a Digester instance", digester);
        assertFalse("Default namespaceAware", digester.getNamespaceAware());
        assertTrue("Default useContextClassLoader", digester.getUseContextClassLoader());
        assertFalse("Default validating", digester.getValidating());

        // Validate the "ruleSet" property
        ConfigRuleSet ruleSet = (ConfigRuleSet) this.parser.getRuleSet();
        assertNotNull("Returned a RuleSet instance", ruleSet);
        assertEquals("Default chainElement", "chain", ruleSet.getChainElement());
        assertEquals("Default classAttribute", "className", ruleSet.getClassAttribute());
        assertEquals("Default commandElement", "command", ruleSet.getCommandElement());
        assertEquals("Default nameAttribute", "name", ruleSet.getNameAttribute());
        assertNull("Default namespaceURI", ruleSet.getNamespaceURI());

        // Validate the "useContextClassLoader" property
        assertTrue("Defaults to use context class loader", this.parser.getUseContextClassLoader());

        // Ensure that there are no preconfigured commands in the catalog
        assertThat(this.catalog, HasCommandCount.hasCommandCount(0));

    }

    /**
     * Load the specified catalog from the specified resource path
     * @param path String
     */
    private void load(final String path) {
        URL url = XmlConfigParserTestCase.class.getResource(path);

        if (url == null) {
            String msg = String.format("Can't find resource for path: %s", path);
            throw new IllegalArgumentException(msg);
        }

        CatalogFactory<String, Object, Context<String, Object>> catalogFactory =
                this.parser.parse(url);
        this.catalog = catalogFactory.getCatalog("foo");
    }

}
