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

/**
 * For testing many-to-many bidirectional relationships of beans with composite Primary Keys.
 * This test is like F_Relation_mnbEC2 test.
 * @author J. Camilleri, H. Joanin
 *
 * This is an advanced test suite for home interface on entity bean CMP2.
 * Beans used: pkcomp/A1, pkcomp/A2
 *
 **/
public class F_Relation_pkcompEC2 extends A_Cmp2Util {

    static Hashtable tbRelationA2B = new Hashtable();


    static {
        tbRelationA2B.put("a-0", new String[]{});
        tbRelationA2B.put("a-1", new String[]{"b-1", "b-2"});
        tbRelationA2B.put("a-2", new String[]{"b-1", "b-2", "b-3"});
        tbRelationA2B.put("a-3", new String[]{"b-2", "b-3", "b-4"});
        // Translate the String[] to a Collection of BPK (Primary Key of the bean B)
        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++) {
                BPK bpk = new BPK(getStringBeforeDash(tb[i]), getIntAfterDash(tb[i]));
                col.add(bpk);
            }
            tbRelationA2B.put(aname, col);
        }
    }

    static Hashtable tbRelationB2A = new Hashtable();

    static {
        tbRelationB2A.put("b-0", new String[]{});
        tbRelationB2A.put("b-1", new String[]{"a-1", "a-2"});
        tbRelationB2A.put("b-2", new String[]{"a-1", "a-2", "a-3"});
        tbRelationB2A.put("b-3", new String[]{"a-2", "a-3"});
        tbRelationB2A.put("b-4", new String[]{"a-3"});
        // Translate the String[] to a Collection of APK (Primary Key of the bean A)
        for (Enumeration eb = tbRelationB2A.keys(); eb.hasMoreElements();) {
            String bname = (String) (eb.nextElement());
            String[] tb = (String[]) tbRelationB2A.get(bname);
            ArrayList col = new ArrayList(tb.length);
            for (int i = 0; i < tb.length; i++) {
                APK apk = new APK(getStringBeforeDash(tb[i]), getIntAfterDash(tb[i]));
                col.add(apk);
            }
            tbRelationB2A.put(bname, col);
        }
    }

    private static String BEAN_HOME_A = "relation_pkcomp_AHome";
    protected static AHomeRemote ahome = null;
    private static String BEAN_HOME_B = "relation_pkcomp_BHome";
    protected static BHomeRemote bhome = null; 


    public F_Relation_pkcompEC2(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("pkcomp", 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(new APK("a", 0));
                } catch (Exception e) {
                    try {
                        utx.begin();
                        ARemote a0 = ahome.create("a", 0);
                        ARemote a1 = ahome.create("a", 1);
                        ARemote a2 = ahome.create("a", 2);
                        ARemote a3 = ahome.create("a", 3);
                        bhome.create("b", 0);
                        bhome.create("b", 1);
                        bhome.create("b", 2);
                        bhome.create("b", 3);
                        bhome.create("b", 4);
                        a1.assignB((Collection) tbRelationA2B.get("a-1"));
                        a2.assignB((Collection) tbRelationA2B.get("a-2"));
                        a3.assignB((Collection) tbRelationA2B.get("a-3"));
                    } catch (Exception i) {
                        fail("InitialState creation problem: " + i);
                    } finally {
                        try {
                            utx.commit();
                        } catch (Exception ii) {
                            debug("Cannot commit table creation" + 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) {
                debug("Cannot check initial state: " + e);
            }
            if (!ok) {
                isInit = false;
                unloadBeans("pkcomp");
            }
        }
    }

    /*
     * 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());
            APK apk = new APK(getStringBeforeDash(aname), getIntAfterDash(aname));
            ARemote a = ahome.findByPrimaryKey(apk);
            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 eb = tbRelationB2A.keys(); eb.hasMoreElements();) {
            String bname = (String) (eb.nextElement());
            BPK bpk = new BPK(getStringBeforeDash(bname), getIntAfterDash(bname));
            BRemote b = bhome.findByPrimaryKey(bpk);
            Collection colActual1 = b.retrieveA();
            ArrayList colExpected1 = (ArrayList) (tbRelationB2A.get(bname));
            if (!isCollectionEqual(colExpected1, colActual1)) {
                isOk = false;
                msgerror = msgerror.append("Wrong relation for " + bname
                                           + " (expected:" + colExpected1
                                           + ", found:" + colActual1 + ")");
            }
        }
        return isOk;
    }

    /**
     * Remove an element in a relation.
     */
    public void _testCohRemoveInRel(int tx) throws Exception {
        String bRemovedString = "b";
        int bRemovedInt = 4;
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a = ahome.findByPrimaryKey(new APK("a",3));
        if (tx == TX_CONT) {
            a.removeFromBInNewTx(new BPK(bRemovedString, bRemovedInt));
        } else {
            a.removeFromB(new BPK(bRemovedString, bRemovedInt));
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // checking
        Collection ca = a.retrieveB();
        BRemote b4 = bhome.findByPrimaryKey(new BPK("b", 4));
        Collection cb4 = b4.retrieveA();
        if (tx != TX_RB) {
            assertEquals("Wrong relations size for a-3: ", 2, ca.size());
            assertEquals("Wrong relations size for b-4: ", 0, cb4.size());
        } else {
            assertEquals("Wrong relations size for a-3: ", 3, ca.size());
            assertEquals("Wrong relations size for b-4: ", 1, cb4.size());
        }
        // undo
        if (tx != TX_RB) {
            a.addInB(new BPK(bRemovedString, bRemovedInt));
        }
        // check to initial state
        checkIsInitialState();

    }

    public void testCohRemoveInRelTxNo() throws Exception {
        _testCohRemoveInRel(TX_NO);
    }

    public void testCohRemoveInRelTxCall() throws Exception {
        _testCohRemoveInRel(TX_CALL);
    }

    public void testCohRemoveInRelTxCont() throws Exception {
        _testCohRemoveInRel(TX_CONT);
    }

    public void testCohRemoveInRelTxRb() throws Exception {
        _testCohRemoveInRel(TX_RB);
    }

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

}


