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

import static org.apache.commons.chain2.testutils.HasLog.hasLog;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertThat;

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

import org.apache.commons.chain2.Chain;
import org.apache.commons.chain2.ChainException;
import org.apache.commons.chain2.Command;
import org.apache.commons.chain2.Context;
import org.apache.commons.chain2.Processing;
import org.apache.commons.chain2.testutils.AddingCommand;
import org.apache.commons.chain2.testutils.DelegatingCommand;
import org.apache.commons.chain2.testutils.DelegatingFilter;
import org.apache.commons.chain2.testutils.ExceptionCommand;
import org.apache.commons.chain2.testutils.ExceptionFilter;
import org.apache.commons.chain2.testutils.NonDelegatingCommand;
import org.apache.commons.chain2.testutils.NonDelegatingFilter;
import org.apache.commons.chain2.testutils.NullReturningCommand;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;


/**
 * <p>Test case for the <code>ChainBase</code> class.</p>
 *
 * @version $Id$
 */

public class ChainBaseTestCase {


    // ---------------------------------------------------- Instance Variables


    /**
     * The {@link Chain} instance under test.
     */
    private Chain<String, Object, Context<String, Object>> chain = null;


    /**
     * The {@link Context} instance on which to execute the chain.
     */
    private Context<String, Object> context = null;


    // -------------------------------------------------- Overall Test Methods


    /**
     * Set up instance variables required by this test case.
     */
    @Before
    public void setUp() {
        this.chain = new ChainBase<>();
        this.context = new ContextBase();
    }

    /**
     * Tear down instance variables required by this test case.
     */
    @After
    public void tearDown() {
        this.chain = null;
        this.context = null;
    }


    // ------------------------------------------------ Individual Test Methods

    /**
     * nullReturningCommandForcesException
     */
    @Test (expected = ChainException.class)
    public void nullReturningCommandForcesException() {
        this.chain.addCommand(new DelegatingCommand("BeforeNullReturningCommand"));
        this.chain.addCommand(new NullReturningCommand());
        this.chain.addCommand(new NonDelegatingCommand("AfterNullReturningCommand"));

        this.chain.execute(this.context);
    }

    /**
     * Test the ability to add commands
     */
    @Test
    public void testCommands() {

        checkCommandCount(0);

        Command<String, Object, Context<String, Object>> command1 = new NonDelegatingCommand("1");
        this.chain.addCommand(command1);
        checkCommandCount(1);

        Command<String, Object, Context<String, Object>> command2 = new DelegatingCommand("2");
        this.chain.addCommand(command2);
        checkCommandCount(2);

        Command<String, Object, Context<String, Object>> command3 = new ExceptionCommand("3");
        this.chain.addCommand(command3);
        checkCommandCount(3);

    }


    /**
     * Test execution of a single non-delegating command
     */
    @Test
    public void testExecute1a() {
        this.chain.addCommand(new NonDelegatingCommand("1"));
        assertEquals(Processing.FINISHED, this.chain.execute(this.context));
        assertThat(this.context, hasLog("1"));
    }


    /**
     * Test execution of a single delegating command
     */
    @Test
    public void testExecute1b() {
        this.chain.addCommand(new DelegatingCommand("1"));
        assertEquals(Processing.CONTINUE, this.chain.execute(this.context));
        assertThat(this.context, hasLog("1"));
    }


    /**
     * Test execution of a single exception-throwing command
     */
    @Test
    public void testExecute1c() {
        this.chain.addCommand(new ExceptionCommand("1"));
        try {
            this.chain.execute(this.context);
        } catch (final ArithmeticException e) {
            assertEquals("Correct exception id", "1", e.getMessage());
        }
        assertThat(this.context, hasLog("1"));
    }


    /**
     * Test execution of an attempt to add a new Command while executing
     */
    @Test
    public void testExecute1d() {
        this.chain.addCommand(new AddingCommand("1", this.chain));
        try {
            this.chain.execute(this.context);
        } catch (final IllegalStateException e) {
            // Expected result
            assertEquals(IllegalStateException.class, e.getClass());
        }
        assertThat(this.context, hasLog("1"));
    }


    /**
     * Test execution of a chain that should return true
     */
    @Test
    public void testExecute2a() {
        this.chain.addCommand(new DelegatingCommand("1"));
        this.chain.addCommand(new DelegatingCommand("2"));
        this.chain.addCommand(new NonDelegatingCommand("3"));
        assertEquals(Processing.FINISHED, this.chain.execute(this.context));
        assertThat(this.context, hasLog("1/2/3"));
    }


    /**
     * Test execution of a chain that should return false
     */
    @Test
    public void testExecute2b() {
        this.chain.addCommand(new DelegatingCommand("1"));
        this.chain.addCommand(new DelegatingCommand("2"));
        this.chain.addCommand(new DelegatingCommand("3"));
        assertEquals(Processing.CONTINUE, this.chain.execute(this.context));
        assertThat(this.context, hasLog("1/2/3"));
    }


    /**
     * Test execution of a chain that should throw an exception
     */
    @Test
    public void testExecute2c() {
        this.chain.addCommand(new DelegatingCommand("1"));
        this.chain.addCommand(new DelegatingCommand("2"));
        this.chain.addCommand(new ExceptionCommand("3"));
        try {
            this.chain.execute(this.context);
        } catch (final ArithmeticException e) {
            assertEquals("Correct exception id", "3", e.getMessage());
        }
        assertThat(this.context, hasLog("1/2/3"));
    }


    /**
     * Test execution of a chain that should throw an exception in the middle
     */
    @Test
    public void testExecute2d() {
        this.chain.addCommand(new DelegatingCommand("1"));
        this.chain.addCommand(new ExceptionCommand("2"));
        this.chain.addCommand(new NonDelegatingCommand("3"));
        try {
            this.chain.execute(this.context);
        } catch (final ArithmeticException e) {
            assertEquals("Correct exception id", "2", e.getMessage());
        }
        assertThat(this.context, hasLog("1/2"));
    }


    /**
     * Test execution of a single non-delegating filter
     */
    @Test
    public void testExecute3a() {
        this.chain.addCommand(new NonDelegatingFilter("1", "a"));
        assertEquals(Processing.FINISHED, this.chain.execute(this.context));
        assertThat(this.context, hasLog("1/a"));
    }


    /**
     * Test execution of a single delegating filter
     */
    @Test
    public void testExecute3b() {
        this.chain.addCommand(new DelegatingFilter("1", "a"));
        assertEquals(Processing.CONTINUE, this.chain.execute(this.context));
        assertThat(this.context, hasLog("1/a"));
    }


    /**
     * Test execution of a single exception-throwing filter
     */
    @Test
    public void testExecute3c() {
        this.chain.addCommand(new ExceptionFilter("1", "a"));
        try {
            this.chain.execute(this.context);
        } catch (final ArithmeticException e) {
            assertEquals("Correct exception id", "1", e.getMessage());
        }
        assertThat(this.context, hasLog("1/a"));
    }


    /**
     * Test execution of a chain that should return true
     */
    @Test
    public void testExecute4a() {
        this.chain.addCommand(new DelegatingFilter("1", "a"));
        this.chain.addCommand(new DelegatingCommand("2"));
        this.chain.addCommand(new NonDelegatingFilter("3", "c"));
        assertEquals(Processing.FINISHED, this.chain.execute(this.context));
        assertThat(this.context, hasLog("1/2/3/c/a"));
    }


    /**
     * Test execution of a chain that should return false
     */
    @Test
    public void testExecute4b() {
        this.chain.addCommand(new DelegatingCommand("1"));
        this.chain.addCommand(new DelegatingFilter("2", "b"));
        this.chain.addCommand(new DelegatingCommand("3"));
        assertEquals(Processing.CONTINUE, this.chain.execute(this.context));
        assertThat(this.context, hasLog("1/2/3/b"));
    }


    /**
     * Test execution of a chain that should throw an exception
     */
    @Test
    public void testExecute4c() {
        this.chain.addCommand(new DelegatingFilter("1", "a"));
        this.chain.addCommand(new DelegatingFilter("2", "b"));
        this.chain.addCommand(new ExceptionFilter("3", "c"));
        try {
            this.chain.execute(this.context);
        } catch (final ArithmeticException e) {
            assertEquals("Correct exception id", "3", e.getMessage());
        }
        assertThat(this.context, hasLog("1/2/3/c/b/a"));
    }


    /**
     * Test execution of a chain that should throw an exception in the middle
     */
    @Test
    public void testExecute4d() {
        this.chain.addCommand(new DelegatingFilter("1", "a"));
        this.chain.addCommand(new ExceptionFilter("2", "b"));
        this.chain.addCommand(new NonDelegatingFilter("3", "c"));
        try {
            this.chain.execute(this.context);
        } catch (final ArithmeticException e) {
            assertEquals("Correct exception id", "2", e.getMessage());
        }
        assertThat(this.context, hasLog("1/2/b/a"));
    }


    /**
     * Test state of newly created instance
     */
    @Test
    public void testNewInstance() {
        checkCommandCount(0);
    }

    /**
     * testConstructorCommandNull
     */
    @Test(expected = IllegalArgumentException.class)
    public void testConstructorCommandNull() {
        assertNotNull(new ChainBase<>((Command<String, Object, Context<String, Object>>) null));
    }

    /**
     * testConstructorVarArgsNull
     */
    @Test(expected = IllegalArgumentException.class)
    public void testConstructorVarArgsNull() {
        assertNotNull(new ChainBase<>((Command<String, Object, Context<String, Object>>[]) null));
    }

    /**
     * testConstructorVarArgsWithNullElements
     */
    @Test(expected = IllegalArgumentException.class)
    public void testConstructorVarArgsWithNullElements() {
        assertNotNull(new ChainBase<>(
                new DelegatingFilter("1", "a"),
                null,
                new ExceptionFilter("2", "b")));
    }

    /**
     * testConstructorCollectionNull
     */
    @Test(expected = IllegalArgumentException.class)
    public void testConstructorCollectionNull() {
        assertNotNull(new ChainBase<>(
                (Collection<Command<String, Object, Context<String, Object>>>) null));
    }

    /**
     * testConstructorCollectionWithNullElements
     */
    @Test(expected = IllegalArgumentException.class)
    public void testConstructorCollectionWithNullElements() {
        List<Command<String, Object, Context<String, Object>>> commands = new ArrayList<>();
        commands.add(new DelegatingFilter("1", "a"));
        commands.add(null);
        commands.add(new ExceptionFilter("2", "b"));
        assertNotNull(new ChainBase<>(commands));
    }


    // -------------------------------------------------------- Support Methods


    // Verify the number of configured commands
    protected void checkCommandCount(final int expected) {
        if (this.chain != null) {
            List<Command<String, Object, Context<String, Object>>> commands =
                ((ChainBase<String, Object, Context<String, Object>>) this.chain).getCommands();
            assertNotNull("getCommands() returned null", commands);
            assertEquals("Command count doesn't match", expected, commands.size());
        }
    }

}
