/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.essar.automation.dhaval.invoker.store.test;

import com.essar.automation.dhaval.invoker.store.*;
import java.lang.reflect.Method;
import java.util.List;

/**
 *
 * @author dhaval
 */
public class Main {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) throws Exception{
        OdbUtil db = new OdbUtil("d:\\dev\\db4o\\ObjectDb");

//        deleteAll(db);
        insert(db);
//        read(db);
        invoke(db);

        db.close();
    }

    public static void deleteAll(OdbUtil db){
        List list = (List) db.get(InvokerMap.class);
        for(Object obj : list){
            db.delete(obj);
        }
    }

    public static void insert(OdbUtil db){
        InvokerMap map = new InvokerMap();
        List list = (List) db.get(InvokerMap.class);
        if(list.size() > 0){
            System.out.println("Total Map..." + list.size() + ", " + list);
            map = (InvokerMap) list.get(list.size()-1);
            System.out.println("Already Invokers..." + map.get("InventoryService").size() + map.get("InventoryService"));
        }

        Invoker in1 = new Invoker();
        in1.setClazz(Hello.class);
        in1.setMethodName("sayHello");
        in1.setMethodParamTypes(new Class[]{String.class});
        in1.setMethodArgs(new Object[]{"rahul kumar"});
        map.add("InventoryService", in1);
        System.out.println("inserted...");

        db.store(map);
    }

    public static void invoke(OdbUtil db) throws Exception {
        List<InvokerMap> resultSet = (List<InvokerMap>) db.get(InvokerMap.class);
        for(InvokerMap map : resultSet){
            List<Invoker> invokers = map.get("InventoryService");
            for(Invoker invk : invokers){
                Method method = invk.getClazz().getMethod(invk.getMethodName(), invk.getMethodParamTypes());
                Object target = invk.getClazz().newInstance();
                System.out.println("Invoking...");
                method.invoke(target, invk.getMethodArgs());
            }
        }

    }

    public static void read(OdbUtil db){
        List resultSet = (List) db.get(InvokerMap.class);
        InvokerMap map = null;
        
        if(resultSet.size() > 0){
            map = (InvokerMap) resultSet.get(resultSet.size()-1);
        }

        if(map == null){
            System.out.println("No Map Found");
            return;
        }

        List<Invoker> invokers = map.get("InventoryService");
        if(invokers == null){
            System.out.println("No Invokers Found");
        }else{
            System.out.println("Invokers found..." + invokers.size() + ", " + invokers);
        }
    }

    public static class Hello{
        public void sayHello(String name){
            System.out.println("Hello, " + name);
        }
    }
}
