/*
 * 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.mnu.AHomeRemote;
import org.objectweb.jonas.jtests.beans.relation.mnu.ARemote;
import org.objectweb.jonas.jtests.beans.relation.mnu.BHomeRemote;
import org.objectweb.jonas.jtests.beans.relation.mnu.BRemote;

/** 
 * For testing many-to-many unidirectional relationships
 * @author S.Chassande-Barrioz, J. Camilleri
 *
 **/
public class G_Relation_mnuEC2 extends A_Cmp2Util {

    static Hashtable tbRelationA2B = new Hashtable();
    static {
        tbRelationA2B.put("a0", new String[]{});
        tbRelationA2B.put("a1", new String[]{"b1","b2"});
        tbRelationA2B.put("a2", new String[]{"b1", "b2", "b3"});
        tbRelationA2B.put("a3", new String[]{"b2","b3","b4"});
        // 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);
        }
    }

    private static String BEAN_HOME_A = "relation_mnu_AHome";
    protected static AHomeRemote ahome = null;
    private static String BEAN_HOME_B = "relation_mnu_BHome";
    protected static BHomeRemote bhome = null;
    

    public G_Relation_mnuEC2(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("mnu", 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();
                        ARemote a0 = ahome.create("a0");
                        ARemote a1 = ahome.create("a1");
                        ARemote a2 = ahome.create("a2");
                        ARemote a3 = ahome.create("a3");
                        bhome.create("b0");
                        bhome.create("b1");
                        bhome.create("b2");
                        bhome.create("b3");
                        bhome.create("b4");
                        a0.assignB((Collection) tbRelationA2B.get("a0"));
                        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("mnu");
            }
        }
    }

    /*
     * 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));
            if (!isCollectionEqual(colExpected, colActual)) {
                isOk = false;
                msgerror = msgerror.append("Wrong relation for " + aname
                                           +" (expected:" + colExpected
                                           + ", found:" + colActual + ")");
            }
        }
        return isOk;
    }


    /**
     * Check that the bean 'a3' has no relation.
     */
    public void _testBasicGetEmpty(int tx) throws Exception {
        Collection c;
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a = ahome.findByPrimaryKey("a0");
        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);
    }
   

    /**
     * Ckeck the new relation a0-b0
     */
    public void _testBasicSetEmpty(int tx) throws Exception {
        ArrayList c = new ArrayList(1);
        c.add("b0");
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a = ahome.findByPrimaryKey("a0");
        if (tx == TX_CONT) {
            a.assignBInNewTx(c);
        } else {
            a.assignB(c);
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // checking
        Collection c_value = a.retrieveB();
        if (tx != TX_RB) {
            assertTrue("Wrong relations a0 (required:" + c + ", found:" + c_value
                       + ")", isCollectionEqual(c_value, c));
            // undo
            a.assignB(new ArrayList(0));
        }
        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);
    }
    /**
     * See 10.3.7.7 of spec  : a1.assignB(a3.retrieveB()) => 
     *   a1.retreiveB().contains("b2") &&
     *   a1.retreiveB().contains("b3") &&
     *   a1.retreiveB().contains("b4") &&
     *   a3.retreiveB().contains("b2") &&
     *   a3.retreiveB().contains("b3") &&
     *   a3.retreiveB().contains("b4") &&
     */
    public void _testBasicSetFirst(int tx) throws Exception {
        String c = null;
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a1 = ahome.findByPrimaryKey("a1");
        ARemote a3 = ahome.findByPrimaryKey("a3");
        Collection c1 = a1.retrieveB();
        if (tx == TX_CONT) {
            a1.assignBInNewTx(a3.retrieveB());
        } else {
            a1.assignB(a3.retrieveB());
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // checking
        if (tx != TX_RB) {
            ArrayList c1_att = new ArrayList(3);
            c1_att.add("b2");
            c1_att.add("b3");
            c1_att.add("b4");
            assertTrue("Wrong test of coherence First before commit: ", isCollectionEqual(a1.retrieveB(),c1_att));
        } else {
            assertTrue("Wrong test of coherence First before roolback: ", isCollectionEqual(a1.retrieveB(),c1));
        }
        // undo
        if (tx != TX_RB) {
            a1.assignB(null);
            a1.assignB(c1);
        }
        checkIsInitialState();
    }
   
  

    /**
     * See  10.3.7.7 of spec : a1.getB().add(b3) => 
     *   a1.retreiveB().contains("b1") &&
     *   a1.retreiveB().contains("b2") &&
     *   a1.retreiveB().contains("b3") &&
     */
    public void _testBasicSetSecond(int tx) throws Exception {
        String c = null;

        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a1 = ahome.findByPrimaryKey("a1");
        Collection c1 = a1.retrieveB();
  
        if (tx == TX_CONT) {
            a1.addInB("b3");
        } else {
            a1.addInB("b3");
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // checking
        if (tx != TX_RB) {
            ArrayList c1_att = new ArrayList(3);
            c1_att.add("b1");
            c1_att.add("b2");
            c1_att.add("b3");
            assertTrue("Wrong test of coherence Second before commit: ", isCollectionEqual(a1.retrieveB(),c1_att));
        } else {
            assertTrue("Wrong test of coherence Second before roolback: ", isCollectionEqual(a1.retrieveB(),c1));
        }
        // undo
        if (tx != TX_RB) {
            a1.assignB(null);
            a1.assignB(c1);
        }
        checkIsInitialState();
    }

 
  


    /**
     * See  10.3.7.7 of spec : a2.getB().remove(b2) => 
     *   a2.retreiveB().contains("b1") &&
     *   a2.retreiveB().contains("b3") &&
     */
    public void _testBasicSetRemove(int tx) throws Exception {
        String c = null;

        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a2 = ahome.findByPrimaryKey("a2");
        Collection c2 = a2.retrieveB();
        if (tx == TX_CONT) {
            a2.removeFromB("b2");
        } else {
            a2.removeFromB("b2");
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // checking
        if (tx != TX_RB) {
            ArrayList c2_att = new ArrayList(3);
            c2_att.add("b1");
            c2_att.add("b3");
            assertTrue("Wrong test of coherence Remove before commit: ", isCollectionEqual(a2.retrieveB(),c2_att));
        } else {
            assertTrue("Wrong test of coherence Remove before roolback: ", isCollectionEqual(a2.retrieveB(),c2));
        }
        // undo
        if (tx != TX_RB) {
            a2.assignB(c2);
        }
        checkIsInitialState();
    }

  
 
    /**
     * Ckeck clear function
     */
    public void _testBasicClear(int tx) throws Exception {
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a2 = ahome.findByPrimaryKey("a2");
        if (tx == TX_CONT) {
            a2.clearBInNewTx();
        } else {
            a2.clearB();
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // checking
        Collection a2_value = a2.retrieveB();
        BRemote b1 = bhome.findByPrimaryKey("b1");
        BRemote b2 = bhome.findByPrimaryKey("b2");
        BRemote b3 = bhome.findByPrimaryKey("b3");
        ArrayList collb1 = new ArrayList(1);
        collb1.add("a1");
        ArrayList collb2 = new ArrayList(2);
        collb2.add("a1");
        collb2.add("a3");
        ArrayList collb3 = new ArrayList(1);
        collb3.add("a3");
        Collection col=null;
        if (tx != TX_RB) {
            assertTrue("Wrong relations a2 (required: Empty  "+", found:" + a2_value
                       + ")", a2_value.isEmpty());
	   
            // undo
            ArrayList a2undo = new ArrayList(3);
            a2undo.add("b1");
            a2undo.add("b2");
            a2undo.add("b3");
            a2.assignB(a2undo);
        }
        checkIsInitialState();
    }

  
   

    /**
     * Remove an element in a relation.
     */
    public void _testCohRemoveInRel(int tx) throws Exception {
        String bRemoved = "b4";
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a = ahome.findByPrimaryKey("a3");
        if (tx == TX_CONT) {
            a.removeFromBInNewTx(bRemoved);
        } else {
            a.removeFromB(bRemoved);
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // checking
        Collection ca = a.retrieveB();
        if (tx != TX_RB) {
            assertEquals("Wrong relations size for a3: ", 2, ca.size());
        } else {
            assertEquals("Wrong relations size for a3: ", 3, ca.size());
        }
        // undo
        if (tx != TX_RB) {
            a.addInB(bRemoved);
        }
        // check to initial state
        checkIsInitialState();

    }

   
    public static Test suite() {
        return new TestSuite(G_Relation_mnuEC2.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_mnuEC2(testtorun));
        }
    }

}
