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

/**
 * For testing many-to-many bidirectional relationships
 * @author S.Chassande-Barrioz, J. Camilleri
 *
 *
 **/
public class G_Relation_mnbEC2 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);
        }
    }

    static Hashtable tbRelationB2A = new Hashtable();

    static {
        tbRelationB2A.put("b0", new String[]{});
        tbRelationB2A.put("b1", new String[]{"a1", "a2"});
        tbRelationB2A.put("b2", new String[]{"a1", "a2", "a3"});
        tbRelationB2A.put("b3", new String[]{"a2", "a3"});
        tbRelationB2A.put("b4", new String[]{"a3"});
        // Translate the String[] to a Collection of String
        for (Enumeration ea1 = tbRelationB2A.keys(); ea1.hasMoreElements();) {
            String aname1 = (String) (ea1.nextElement());
            String[] tb1 = (String[]) tbRelationB2A.get(aname1);
            ArrayList col1 = new ArrayList(tb1.length);
            for (int j = 0; j < tb1.length; j++) {
                col1.add(tb1[j]);
            }
            tbRelationB2A.put(aname1, col1);
        }
    }

    private static String BEAN_HOME_A = "relation_mnb_AHome";
    protected static AHomeRemote ahome = null;
    private static String BEAN_HOME_B = "relation_mnb_BHome";
    protected static BHomeRemote bhome = null;


    public G_Relation_mnbEC2(String name) {
        super(name);
    }
  
  
    public void testEmpty() throws Exception {
    }
    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("mnb", false);
                // lookup home used in the tests
                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 {
                        // IMPORTANT: comments begin/commit to highlight a bug
                        utx.begin();
                        ahome.create("a0");
                        ahome.create("a1");
                        ahome.create("a2");
                        ahome.create("a3");
                        bhome.create("b0");
                        bhome.create("b1");
                        bhome.create("b2");
                        bhome.create("b3");
                        bhome.create("b4");
                        ARemote a0 = ahome.findByPrimaryKey("a0");
                        ARemote a1 = ahome.findByPrimaryKey("a1");
                        ARemote a2 = ahome.findByPrimaryKey("a2");
                        ARemote a3 = ahome.findByPrimaryKey("a3");
                        Collection  rel_a0 = (Collection) (tbRelationA2B.get("a0"));
                        a0.assignB(rel_a0);
                        Collection rel_a1 = (Collection) (tbRelationA2B.get("a1"));
                        a1.assignB(rel_a1);	
                        Collection rel_a2 = (Collection) (tbRelationA2B.get("a2"));
                        a2.assignB(rel_a2);	
                        Collection  rel_a3 = (Collection) (tbRelationA2B.get("a3"));
                        a3.assignB(rel_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) {
                debug("F_Relation_mnbEC2 setUp: unload bean and retry");
                isInit = false;
                unloadBeans("mnb");
            }
        }
    }

    /*
     * 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();
        // Check relations A to B
        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 + ")");
            }
        }
        // Check Relations B to A
        for (Enumeration ea1 = tbRelationB2A.keys(); ea1.hasMoreElements();) {
            String aname1 = (String) (ea1.nextElement());
            BRemote b = bhome.findByPrimaryKey(aname1);
            Collection colActual1 = b.retrieveA();
            ArrayList colExpected1 = (ArrayList) (tbRelationB2A.get(aname1));
            if (!isCollectionEqual(colExpected1, colActual1)) {
                isOk = false;
                msgerror = msgerror.append("Wrong relation for " + aname1
                                           + " (expected:" + colExpected1
                                           + ", found:" + colActual1 + ")");
            }
        }
        return isOk;
    }

    /**
     * Check that the bean 'a0' 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));
        } else {
            assertTrue("Wrong relation a0->b0 : ", c_value.isEmpty());
        }
        // undo
        if (tx != TX_RB) {
            a.assignB(new ArrayList());
        }
        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);
    }

    /**
     * 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());
            col = bhome.findByPrimaryKey("b1").retrieveA();
            assertTrue("Wrong collection returned by b1.getA(): expected:" + collb1
                       + " found: " + col, isCollectionEqual(collb1, col));
            col = bhome.findByPrimaryKey("b2").retrieveA();
            assertTrue("Wrong collection returned by b2.getA(): expected:" + collb2
                       + " found: " + col, isCollectionEqual(collb2, col));
            col = bhome.findByPrimaryKey("b3").retrieveA();
            assertTrue("Wrong collection returned by b3.getA(): expected:" + collb3
                       + " found: " + col, isCollectionEqual(collb3, col));
            // undo
            ArrayList a2undo = new ArrayList(3);
            a2undo.add("b1");
            a2undo.add("b2");
            a2undo.add("b3");
            a2.assignB(a2undo);
        }
        checkIsInitialState();
    }

  
 

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

}
