/**
 * Copyright 2010 OpenEngSB Division, Vienna University of Technology
 *
 * Licensed 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.openengsb.core.workflow.flow;

import java.io.File;
import java.net.URL;

import org.apache.commons.io.FileUtils;
import org.drools.KnowledgeBase;
import org.drools.event.process.DefaultProcessEventListener;
import org.drools.event.process.ProcessCompletedEvent;
import org.drools.runtime.StatefulKnowledgeSession;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.openengsb.core.workflow.RuleBaseException;
import org.openengsb.core.workflow.RuleManager;
import org.openengsb.core.workflow.internal.dirsource.DirectoryRuleSource;
import org.openengsb.core.workflow.model.RuleBaseElementId;
import org.openengsb.core.workflow.model.RuleBaseElementType;
import org.openengsb.core.workflow.model.TestObject;

import static org.hamcrest.CoreMatchers.notNullValue;

import static org.junit.Assert.assertThat;

public class RuleManagerFlowTest {

    private RuleManager source;
    private KnowledgeBase rulebase;
    private StatefulKnowledgeSession session;

    @Before
    public void setUp() throws Exception {
        source = getRuleBaseSource();
        rulebase = source.getRulebase();
    }

    @After
    public void tearDown() throws Exception {
        if (session != null) {
            session.dispose();
        }
    }

    @After
    @Before
    public void deleteData() throws Exception {
        File ruleDir = new File("data");
        while (ruleDir.exists()) {
            FileUtils.deleteQuietly(ruleDir);
        }
    }

    protected RuleManager getRuleBaseSource() throws RuleBaseException {
        DirectoryRuleSource source = new DirectoryRuleSource("data/rulebase");
        source.init();
        return source;
    }

    @Test
    public void testAddFlow() throws Exception {
        source.addImport(TestObject.class.getName());
        URL systemResource = ClassLoader.getSystemResource("flowtest.rf");
        File flowFile = FileUtils.toFile(systemResource);
        String flowString = FileUtils.readFileToString(flowFile);
        source.add(new RuleBaseElementId(RuleBaseElementType.Process, "flowtest"), flowString);
        assertThat(source.get(new RuleBaseElementId(RuleBaseElementType.Process, "flowtest")), notNullValue());
    }

    @Test(timeout = 3000)
    public void testRunFlow() throws Exception {
        source.addImport(TestObject.class.getName());
        URL systemResource = ClassLoader.getSystemResource("flowtest.rf");
        File flowFile = FileUtils.toFile(systemResource);
        String flowString = FileUtils.readFileToString(flowFile);
        source.add(new RuleBaseElementId(RuleBaseElementType.Process, "flowtest"), flowString);
        session = rulebase.newStatefulKnowledgeSession();
        session.addEventListener(new DefaultProcessEventListener() {
            @Override
            public void afterProcessCompleted(ProcessCompletedEvent event) {
                session.halt();
            }
        });
        Thread t = new Thread() {
            @Override
            public void run() {
                session.fireUntilHalt();
            };
        };
        t.start();
        session.startProcess("flowtest");
        t.join();
        session.dispose();
    }
}

@@ -753,16 +753,101 @@
 eUtils;%0A
+import org.apache.commons.logging.Log;%0Aimport org.apache.commons.logging.LogFactory;%0A
 import o
@@ -871,16 +871,16 @@
 geBase;%0A
-
 import o
@@ -1035,24 +1035,75 @@
 dgeSession;%0A
+import org.drools.runtime.process.ProcessInstance;%0A
 import org.j
@@ -1650,16 +1650,85 @@
 Test %7B%0A%0A
+    private Log log = LogFactory.getLog(RuleManagerFlowTest.class);%0A%0A
     priv
@@ -3931,24 +3931,24 @@
  t.start();%0A
-
         sess
@@ -4027,11 +4027,1416 @@
 );%0A    %7D
+%0A%0A    @Test(timeout = 10000)%0A    public void testRunFlowWithEvents() throws Exception %7B%0A        source.addImport(TestObject.class.getName());%0A        source.add(new RuleBaseElementId(RuleBaseElementType.Global, %22log%22), Log.class.getName());%0A%0A        URL systemResource = ClassLoader.getSystemResource(%22floweventtest.rf%22);%0A        File flowFile = FileUtils.toFile(systemResource);%0A        String flowString = FileUtils.readFileToString(flowFile);%0A        source.add(new RuleBaseElementId(RuleBaseElementType.Process, %22flowtest%22), flowString);%0A        session = rulebase.newStatefulKnowledgeSession();%0A        session.setGlobal(%22log%22, log);%0A        session.addEventListener(new DefaultProcessEventListener() %7B%0A            @Override%0A            public void afterProcessCompleted(ProcessCompletedEvent event) %7B%0A                session.halt();%0A            %7D%0A        %7D);%0A        Thread t = new Thread() %7B%0A            @Override%0A            public void run() %7B%0A                session.fireAllRules();%0A            %7D;%0A        %7D;%0A        t.start();%0A        ProcessInstance startProcess = session.startProcess(%22flowtest%22);%0A        startProcess.signalEvent(%22TestObject%22, new TestObject());%0A        /*%0A         * invoking: session.signalEvent(%22TestObject%22, new TestObject()); does not work%0A         */%0A        startProcess.signalEvent(%22TestObject2%22, new TestObject());%0A        t.join();%0A        session.dispose();%0A    %7D
 %0A%7D%0A

add test for rulemanager and ruleflow with event-handling