/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@objectweb.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.jtests.clients.entity;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;

import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

import junit.framework.Test;
import junit.framework.TestSuite;

import org.objectweb.jonas.jtests.beans.relation.omu.AHomeRemote;
import org.objectweb.jonas.jtests.beans.relation.omu.ARemote;
import org.objectweb.jonas.jtests.beans.relation.omu.BHomeRemote;


/**
 * For testing one-to-many unidirectional relationships
 * @author S.Chassande-Barrioz, Helene Joanin
 */

public class G_Relation_omuEC2 extends A_Cmp2Util {


    private static String BEAN_HOME_A = "relation_omu_AHome";
    protected static AHomeRemote ahome = null;
    private static String BEAN_HOME_B = "relation_omu_BHome";
    protected static BHomeRemote bhome = null;

    static Hashtable tbRelationA2B = new Hashtable();

    static {
        tbRelationA2B.put("as0", new String[]{});
        tbRelationA2B.put("as1", new String[]{"bs1_1"});
        tbRelationA2B.put("as2", new String[]{"bs2_1", "bs2_2", "bs2_3"});
        tbRelationA2B.put("a0", new String[]{});
        tbRelationA2B.put("a1", new String[]{"b1_1", "b1_2", "b1_3"});
        tbRelationA2B.put("a2", new String[]{"b2_1", "b2_2", "b2_3"});
        tbRelationA2B.put("a3", new String[]{"b3_1"});
        // Translate the String[] to a Collection of String
        for (Enumeration ea = tbRelationA2B.keys(); ea.hasMoreElements();) {
            String aname = (String) (ea.nextElement());
            String[] tb = (String[]) tbRelationA2B.get(aname);
            ArrayList col = new ArrayList(tb.length);
            for (int i = 0; i < tb.length; i++) {
                col.add(tb[i]);
            }
            tbRelationA2B.put(aname, col);
        }
    }

    public G_Relation_omuEC2(String name) {
        super(name);
    }
  
    protected boolean isInit = false;

    protected void setUp() {
        super.setUp();
        boolean ok = false;
        int nbtry = 0;
        while (!ok && nbtry < 3) {
            if (!isInit) {
                // load bean if not loaded yet
                useBeans("omu", false);
                try {
                    ahome = (AHomeRemote) PortableRemoteObject.narrow(ictx.lookup(BEAN_HOME_A),
                                                                      AHomeRemote.class);
                    bhome = (BHomeRemote) PortableRemoteObject.narrow(ictx.lookup(BEAN_HOME_B),
                                                                      BHomeRemote.class);
                } catch (NamingException e) {
                    fail("Cannot get bean home: " + e.getMessage());
                }
                // check if tables have been initialized
                try {
                    ahome.findByPrimaryKey("a0");
                } catch (Exception e) {
                    try {
                        utx.begin();
                        bhome.create("bs0");
                        bhome.create("bs1_1");
                        bhome.create("bs2_1");
                        bhome.create("bs2_2");
                        bhome.create("bs2_3");
                        bhome.create("bs3");
                        bhome.create("b0");
                        bhome.create("b1_1");
                        bhome.create("b1_2");
                        bhome.create("b1_3");
                        bhome.create("b2_1");
                        bhome.create("b2_2");
                        bhome.create("b2_3");
                        bhome.create("b3_1");
                        ARemote as0 = ahome.create("as0");
                        ARemote as1 = ahome.create("as1");
                        ARemote as2 = ahome.create("as2");
                        ARemote a0 = ahome.create("a0");
                        ARemote a1 = ahome.create("a1");
                        ARemote a2 = ahome.create("a2");
                        ARemote a3 = ahome.create("a3");
                        as1.assignB((Collection)tbRelationA2B.get("as1"));
                        as2.assignB((Collection)tbRelationA2B.get("as2"));
                        a1.assignB((Collection)tbRelationA2B.get("a1"));
                        a2.assignB((Collection)tbRelationA2B.get("a2"));
                        a3.assignB((Collection)tbRelationA2B.get("a3"));
                    } catch (Exception i) {
                        fail("InitialState creation problem:: "+i);
                    } finally {
                        try {
                            utx.commit();
                        } catch (Exception ii) {
                        }
                    }
                }
                isInit = true;
            }
            // Check that all is OK. Sometimes, a test has failed and has corrupted
            // the bean state in the database. We must unload and reload the bean then.
            nbtry++;
            try {
                if (initStateOK()) {
                    ok = true;
                }
            } catch (Exception e) {
            }
            if (!ok) {
                isInit = false;
                unloadBeans("omu");
            }
        }
    }

    /*
     * Check that we are in the same state as after the tables creation for thoses beans A and B
     * (ie if it is the initial state)
     */
    boolean initStateOK() throws Exception {
        boolean isOk = true;
        msgerror = new StringBuffer();
        for (Enumeration ea = tbRelationA2B.keys(); ea.hasMoreElements();) {
            String aname = (String) (ea.nextElement());
            ARemote a = ahome.findByPrimaryKey(aname);
            Collection colActual = a.retrieveB();
            ArrayList colExpected = (ArrayList) (tbRelationA2B.get(aname));
            debug("Relation for " + aname + " :: expected:" + colExpected + ", found:" + colActual );
            if (!isCollectionEqual(colExpected, colActual)) {
                isOk = false;
                msgerror = msgerror.append("Wrong relation for " + aname
                                           + " (expected:" + colExpected
                                           + ", found:" + colActual + ")");
            }
        }
        return isOk;
    }



    /**
     * Check that the bean 'as0' has no relation.
     */
    public void _testBasicGetEmpty(int tx) throws Exception {
        Collection c = null;
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a = ahome.findByPrimaryKey("as0");
        if (tx == TX_CONT) {
            c = a.retrieveBInNewTx();
        } else {
            c = a.retrieveB();
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        checkIsInitialState();
    }

      public void testBasicGetEmptyTxNo() throws Exception {
        _testBasicGetEmpty(TX_NO);
    }

    public void testBasicGetEmptyTxCall() throws Exception {
        _testBasicGetEmpty(TX_CALL);
    }

    public void testBasicGetEmptyTxCont() throws Exception {
        _testBasicGetEmpty(TX_CONT);
    }

    /**
     * Check that the bean 'as1' has only one relation with 'bs1_1'.
     */
    public void _testBasicGetOne(int tx) throws Exception {

        Collection c = null;
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a = ahome.findByPrimaryKey("as1");
        if (tx == TX_CONT) {
            c = a.retrieveBInNewTx();
        } else {
            c = a.retrieveB();
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // checking
        assertEquals("Wrong relations size for as1: ", 1, c.size());
        String s = "bs1_1";
        assertTrue("Relation missing " + s + " for as1: ", c.contains(s));
        checkIsInitialState();
    }

  
    /**
     * Check that the bean 'as2' has many relations with 'bs2_1', 'bs2_2', 'bs2_3'.
     */
    public void _testBasicGetMany(int tx) throws Exception {

        Collection c = null;
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a = ahome.findByPrimaryKey("as2");
        if (tx == TX_CONT) {
            c = a.retrieveBInNewTx();
        } else {
            c = a.retrieveB();
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // checking
        assertEquals("Relations size of: ", 3, c.size());
        String s = "bs2_1";
        assertTrue("Relation missing " + s + ": ", c.contains(s));
        s = "bs2_2";
        assertTrue("Relation missing " + s + ": ", c.contains(s));
        s = "bs2_3";
        assertTrue("Relation missing " + s + ": ", c.contains(s));
        checkIsInitialState();
    }

   
 public void _testBasicSetEmpty(int tx) throws Exception {
        ArrayList ce = new ArrayList();
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a = ahome.findByPrimaryKey("as1");
        if (tx == TX_CONT) {
            a.assignBInNewTx(ce);
        } else {
            a.assignB(ce);
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // checking
        Collection ca = a.retrieveB();
        if (tx != TX_RB) {
            assertEquals("Relations size of: ", 0, ca.size());
        } else {
            assertEquals("Relations size of: ", 1, ca.size());
        }
        // undo
        if (tx != TX_RB) {
            a.addInB("bs1_1");
            // Check undo
            ca = a.retrieveB();
            assertEquals("After undo, Relations size of: ", 1, ca.size());
        }
        checkIsInitialState();
    }

    public void testBasicSetEmptyTxNo() throws Exception {
        _testBasicSetEmpty(TX_NO);
    }

    public void testBasicSetEmptyTxCall() throws Exception {
        _testBasicSetEmpty(TX_CALL);
    }

    public void testBasicSetEmptyTxCont() throws Exception {
        _testBasicSetEmpty(TX_CONT);
    }


   

    public static Test suite() {
        return new TestSuite(G_Relation_omuEC2.class);
    }

    public static void main(String args[]) {
        String testtorun = null;
        // Get args
        for (int argn = 0; argn < args.length; argn++) {
            String s_arg = args[argn];
            Integer i_arg;
            if (s_arg.equals("-n")) {
                testtorun = args[++argn];
            }
        }
        if (testtorun == null) {
            junit.textui.TestRunner.run(suite());
        } else {
            junit.textui.TestRunner.run(new G_Relation_omuEC2(testtorun));
        }
    }

}
