/*
 * Copyright (c) 2015, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
 *
 * 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.wso2.carbon.ml.siddhi.extension;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.wso2.carbon.ml.core.utils.MLCoreServiceValueHolder;
import org.wso2.siddhi.core.ExecutionPlanRuntime;
import org.wso2.siddhi.core.SiddhiManager;
import org.wso2.siddhi.core.event.Event;
import org.wso2.siddhi.core.query.output.callback.QueryCallback;
import org.wso2.siddhi.core.stream.input.InputHandler;
import org.wso2.siddhi.core.util.EventPrinter;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Properties;

public class PredictStreamProcessorTestCase {

    private volatile boolean eventArrived;

    @Before
    public void init() {
        MLCoreServiceValueHolder valueHolder = MLCoreServiceValueHolder.getInstance();
        valueHolder.setMlProperties(new Properties());
        eventArrived = false;
    }

    @Test
    public void predictFunctionTest() throws InterruptedException, URISyntaxException {

        URI resource = new URI("file://" + System.getProperty("user.dir") + "/src/test/resources/test-model");
        String modelStorageLocation = new File(resource).getAbsolutePath();

        SiddhiManager siddhiManager = new SiddhiManager();

        String inputStream = "define stream InputStream "
                + "(NumPregnancies double, PG2 double, DBP double, TSFT double, SI2 double, BMI double, DPF double, Age double);";

        String query = "@info(name = 'query1') " + "from InputStream#ml:predict('" + modelStorageLocation + "','double') "
                + "select * " + "insert into outputStream ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inputStream + query);

        executionPlanRuntime.addCallback("query1", new QueryCallback() {
            @Override
            public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                EventPrinter.print(timeStamp, inEvents, removeEvents);
                if (inEvents != null) {
                    Assert.assertEquals(1.0, inEvents[0].getData(8));
                    eventArrived = true;
                }
            }

        });

        InputHandler inputHandler = executionPlanRuntime.getInputHandler("InputStream");
        executionPlanRuntime.start();
        inputHandler.send(new Object[] { 2,84,0,0,0,0.0,0.304,21});
        sleepTillArrive(5001);
        Assert.assertTrue(eventArrived);
        executionPlanRuntime.shutdown();
        siddhiManager.shutdown();
    }

    @Test
    public void predictFunctionWithSelectedAttributesTest() throws InterruptedException, URISyntaxException {

        URI resource = new URI("file://" + System.getProperty("user.dir") + "/src/test/resources/test-model");
        String modelStorageLocation = new File(resource).getAbsolutePath();

        SiddhiManager siddhiManager = new SiddhiManager();

        String inputStream = "define stream InputStream "
                + "(NumPregnancies double, PG2 double, DBP double, TSFT double, SI2 double, BMI double, DPF double, Age double);";

        String query = "@info(name = 'query1') " + "from InputStream#ml:predict('" + modelStorageLocation
                + "', 'double', NumPregnancies, PG2, DBP, TSFT, SI2, BMI, DPF, Age) " + "select * "
                + "insert into outputStream ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inputStream + query);

        executionPlanRuntime.addCallback("query1", new QueryCallback() {
            @Override
            public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                EventPrinter.print(timeStamp, inEvents, removeEvents);
                if (inEvents != null) {
                    Assert.assertEquals(1.0, inEvents[0].getData(8));
                    eventArrived = true;
                }
            }

        });

        InputHandler inputHandler = executionPlanRuntime.getInputHandler("InputStream");
        executionPlanRuntime.start();
        inputHandler.send(new Object[] { 2,84,0,0,0,0.0,0.304,21 });
        sleepTillArrive(5001);
        Assert.assertTrue(eventArrived);
        executionPlanRuntime.shutdown();
    }

    @Test
    public void predictFunctionWithSelectPredictionTest() throws InterruptedException, URISyntaxException {

        URI resource = new URI("file://" + System.getProperty("user.dir") + "/src/test/resources/test-model");
        String modelStorageLocation = new File(resource).getAbsolutePath();

        SiddhiManager siddhiManager = new SiddhiManager();

        String inputStream = "define stream InputStream "
                + "(NumPregnancies double, PG2 double, DBP double, TSFT double, SI2 double, BMI double, DPF double, Age double);";

        String query = "@info(name = 'query1') " + "from InputStream#ml:predict('" + modelStorageLocation
                + "', 'double', NumPregnancies, PG2, DBP, TSFT, SI2, BMI, DPF, Age) " + "select Class "
                + "insert into outputStream ;";

        ExecutionPlanRuntime executionPlanRuntime = siddhiManager.createExecutionPlanRuntime(inputStream + query);

        executionPlanRuntime.addCallback("query1", new QueryCallback() {
            @Override
            public void receive(long timeStamp, Event[] inEvents, Event[] removeEvents) {
                EventPrinter.print(timeStamp, inEvents, removeEvents);
                if (inEvents != null) {
                    Assert.assertEquals(1.0, inEvents[0].getData(0));
                    eventArrived = true;
                }
            }

        });

        InputHandler inputHandler = executionPlanRuntime.getInputHandler("InputStream");
        executionPlanRuntime.start();
        inputHandler.send(new Object[] { 2,84,0,0,0,0.0,0.304,21 });
        sleepTillArrive(5001);
        Assert.assertTrue(eventArrived);
        executionPlanRuntime.shutdown();
    }

    private void sleepTillArrive(int milliseconds) {
        int totalTime = 0;
        while (!eventArrived && totalTime < milliseconds) {
            int t = 1000;
            try {
                Thread.sleep(t);
            } catch (InterruptedException ignore) {
            }
            totalTime += t;
        }
    }
}

@@ -1316,16 +1316,172 @@
 Arrived;
+%0A    private String modelPath = File.separator + %22src%22 + File.separator + %22test%22 + File.separator + %22resources%22%0A            + File.separator + %22test-model%22;
 %0A%0A    @B
@@ -1869,40 +1869,17 @@
 ) + 
-%22/src/test/resources/test-
 model
-%22
+Path
 );%0A 
@@ -3509,40 +3509,17 @@
 ) + 
-%22/src/test/resources/test-
 model
-%22
+Path
 );%0A 
@@ -5183,40 +5183,17 @@
 ) + 
-%22/src/test/resources/test-
 model
-%22
+Path
 );%0A 

fix windows test failures in unit tests.