// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package ejb3.client;

import java.util.Hashtable;
import java.util.stream.IntStream;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;

import ejb3.common.Data;
import ejb3.common.Test;

public class Client {
    // WildFly/JBoss specific:
    private static final String PREFIX = "org.jboss.ejb.client.naming";
    private static final String CTXFAC = "org.jboss.naming.remote.client.InitialContextFactory";
    private static final String URL = "http-remoting://localhost:8080";
    private static final String NAME1 = "ejb/test-ejb3/TestStateless!ejb3.common.Test";
    private static final String NAME2 = "ejb/test-ejb3/TestStateful!ejb3.common.Test";
    static {
        Hashtable<String,Object> props = new Hashtable<>();
        props.put(Context.URL_PKG_PREFIXES, PREFIX);
        props.put(Context.INITIAL_CONTEXT_FACTORY,  CTXFAC);
        props.put(Context.PROVIDER_URL, URL);
        props.put("jboss.naming.client.ejb.context", true);
        try {
            ctx = new InitialContext(props);
        } catch (NamingException e) {
            e.printStackTrace();
        }
    }
    //
    private static Context ctx;
    private static void testFunctional(String name) throws NamingException {
        Test tst = (Test)ctx.lookup(name);
        int a = 123;
        int b = 456;
        int c = tst.add(a,  b);
        System.out.println(c);;
        String s = "ABC";
        String s2 = tst.dup(s);
        System.out.println(s2);
        Data d = new Data(123, "ABC");
        Data d2 = tst.process(d);
        System.out.printf("%d %s\n", d2.getIv(), d2.getSv());
    }
    private static void testInstantiation(String name) throws NamingException {
        Test tst1 = (Test)ctx.lookup(name);
        for(int i = 0; i < 2; i++) {
            int n = tst1.getCounter();
            System.out.println(n);
        }
        Test tst2 = (Test)ctx.lookup(name);
        for(int i = 0; i < 2; i++) {
            int n = tst2.getCounter();
            System.out.println(n);
        }
    }
    private static final int REP = 100000;
    private static void testPerformance(String name) throws NamingException {
        Test tst = (Test)ctx.lookup(name);
        long t1 = System.currentTimeMillis();
        IntStream.range(0, REP).parallel().forEach(i -> { tst.noop(); });
        long t2 = System.currentTimeMillis();
        System.out.printf("%d requests per second\n", REP * 1000 / (t2 - t1));
    }
    public static void test(String label, String name) throws NamingException {
        System.out.println(label + ":");
        testFunctional(name);
        testInstantiation(name);
        testPerformance(name);
    }
    public static void main(String[] args) throws NamingException {
        test("Stateless", NAME1);
        test("Stateful", NAME2);
    }
}
