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

/**
 * For testing many-to-one unidirectional relationships
 * @author Ph. Durieux
 *
 * This is an advanced test suite for home interface on entity bean CMP2.
 **/
public abstract class A_mou extends A_Cmp2Util {

    public abstract AHomeRemote getAHome();
    public abstract BHomeRemote getBHome();


    static Hashtable tbRelationA2B = new Hashtable();

    static {
        tbRelationA2B.put("a20", "b2");
        tbRelationA2B.put("a21", "b2");
        tbRelationA2B.put("a22", "b2");
        tbRelationA2B.put("a0", "b0");
        tbRelationA2B.put("a1", "b0");
        tbRelationA2B.put("a2", "b0");
        tbRelationA2B.put("a3", "");
        tbRelationA2B.put("a4", "b4");
        tbRelationA2B.put("a5", "b4");
    }

    public A_mou(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("mou", false);
                // check if tables have been initialized
                try {
                    getAHome().findByPrimaryKey("a0");
                } catch (Exception e) {
                    // Make the initialization needed for the tests
                    try {
                        utx.begin();
                        ARemote a0 = getAHome().create("a0");
                        ARemote a1 = getAHome().create("a1");
                        ARemote a2 = getAHome().create("a2");
                        ARemote a3 = getAHome().create("a3");
                        ARemote a4 = getAHome().create("a4");
                        ARemote a5 = getAHome().create("a5");
                        ARemote a20 = getAHome().create("a20");
                        ARemote a21 = getAHome().create("a21");
                        ARemote a22 = getAHome().create("a22");
                        getBHome().create("b0");
                        getBHome().create("b1");
                        getBHome().create("b2");
                        getBHome().create("b4");
                        // assign relations only if not null (a3)
                        a0.assignB((String) tbRelationA2B.get("a0"));
                        a1.assignB((String) tbRelationA2B.get("a1"));
                        a2.assignB((String) tbRelationA2B.get("a2"));
                        a4.assignB((String) tbRelationA2B.get("a4"));
                        a5.assignB((String) tbRelationA2B.get("a5"));
                        a20.assignB((String) tbRelationA2B.get("a20"));
                        a21.assignB((String) tbRelationA2B.get("a21"));
                        a22.assignB((String) tbRelationA2B.get("a22"));
                    } catch (Exception e2) {
                        fail("InitialState creation problem: " + e2);
                    } finally {
                        try {
                            utx.commit();
                        } catch (Exception e3) {
                        }
                    }
                }
                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("mou");
            }
        }
    }


    /*
     * 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 = getAHome().findByPrimaryKey(aname);
            String BActual = a.retrieveB();
            // If BActual is empty then convert to "" to match with tbRelationA2B value in this case
            if (BActual == null) BActual = "";
            String BExpected = (String) (tbRelationA2B.get(aname));
            if (!BActual.equals(BExpected)) {
                isOk = false;
                msgerror = msgerror.append("Wrong relation for " + aname
                                           + " (expected:" + BExpected
                                           + ", found:" + BActual + ")");
            }
        }
        return isOk;
    }



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

    public void testBasicGetEmptyTxRb() throws Exception {
        _testBasicGetEmpty(TX_RB);
    }

    /**
     * Ckeck the new relation a3-b1
     */
    public void _testBasicSetEmpty(int tx) throws Exception {
        String c = null;
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a = getAHome().findByPrimaryKey("a3");
        if (tx == TX_CONT) {
            a.assignBInNewTx("b1");
        } else {
            a.assignB("b1");
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // checking
        String idB = a.retrieveB();
        if (tx != TX_RB) {
            assertEquals("Wrong new relation a3->b1 : ", "b1", idB);
        } else {
            assertNull("Wrong new relation a3->b1 : ", idB);
        }
        // undo
        if (tx != TX_RB) {
            a.assignB(null);
        }
        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 void testBasicSetEmptyTxRb() throws Exception {
        _testBasicSetEmpty(TX_RB);
    }

    /**
     * Check that a1.retrieveB()=b0
     */
    public void _testBasicGet(int tx) throws Exception {
        String b = null;
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a1 = getAHome().findByPrimaryKey("a1");

        if (tx == TX_CONT) {
            b = a1.retrieveBInNewTx();
        } else {
            b = a1.retrieveB();
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // checking
        if (tx != TX_RB) {
            assertEquals("Wrong relation a1->b0 : ", "b0", b);
        }
        checkIsInitialState();
    }

    public void testBasicGetTxNo() throws Exception {
        _testBasicGet(TX_NO);
    }

    public void testBasicGetTxCall() throws Exception {
        _testBasicGet(TX_CALL);
    }

    public void testBasicGetTxCont() throws Exception {
        _testBasicGet(TX_CONT);
    }

    public void testBasicGetTxRb() throws Exception {
        _testBasicGet(TX_RB);
    }

    /**
     * Check that a1.assignB(null) => a1.retreiveB()=null
     */
    public void _testBasicSetNull(int tx) throws Exception {
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a1 = getAHome().findByPrimaryKey("a1");

        if (tx == TX_CONT) {
            a1.assignBInNewTx(null);
        } else {
            a1.assignB(null);
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // checking
        if (tx != TX_RB) {
            String b = a1.retrieveB();
            assertNull("Wrong relation a1 : ", b);
            // Undo
            a1.assignB("b0");
        }
        checkIsInitialState();
    }

    public void testBasicSetNullTxNo() throws Exception {
        _testBasicSetNull(TX_NO);
    }

    public void testBasicSetNullTxCall() throws Exception {
        _testBasicSetNull(TX_CALL);
    }

    public void testBasicSetNullTxCont() throws Exception {
        _testBasicSetNull(TX_CONT);
    }

    public void testBasicSetNullTxRb() throws Exception {
        _testBasicSetNull(TX_RB);
    }

    /**
     * See 10.3.7.5 : a1j.assignB(a2k.retrieveB()) => a2=a1j.retrieveB()
     */
    public void _testBasicSet(int tx) throws Exception {
        String c = null;
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a1 = getAHome().findByPrimaryKey("a1");
        ARemote a21 = getAHome().findByPrimaryKey("a21");
        if (tx == TX_CONT) {
            a1.assignBInNewTx(a21.retrieveB());
        } else {
            a1.assignB(a21.retrieveB());
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        if (tx != TX_RB) {
            // checking
            String idB1 = a1.retrieveB();
            ARemote a0 = getAHome().findByPrimaryKey("a0");
            ARemote a2 = getAHome().findByPrimaryKey("a2");
            ARemote a3 = getAHome().findByPrimaryKey("a3");
            ARemote a20 = getAHome().findByPrimaryKey("a20");
            ARemote a22 = getAHome().findByPrimaryKey("a22");
            String idB0 = a0.retrieveB();
            String idB2 = a2.retrieveB();
            String idB3 = a3.retrieveB();
            String idB20 = a20.retrieveB();
            String idB21 = a21.retrieveB();
            String idB22 = a22.retrieveB();
            assertEquals("Wrong new relation a1->b2 : ", "b2", idB1);
            assertEquals("Wrong new relation a0->b0 : ", "b0", idB0);
            assertEquals("Wrong new relation a2->b0 : ", "b0", idB2);
            assertEquals("Wrong new relation a20->b2 : ", "b2", idB20);
            assertEquals("Wrong new relation a21->b2 : ", "b2", idB21);
            assertEquals("Wrong new relation a22->b2 : ", "b2", idB22);
            // undo
            a1.assignB("b0");
        }
        checkIsInitialState();
    }

    public void testBasicSetTxNo() throws Exception {
        _testBasicSet(TX_NO);
    }

    public void testBasicSetTxCall() throws Exception {
        _testBasicSet(TX_CALL);
    }

    public void testBasicSetTxCont() throws Exception {
        _testBasicSet(TX_CONT);
    }

    public void testBasicSetTxRb() throws Exception {
        _testBasicSet(TX_RB);
    }

    /**
     * Test of coherence a0.remove()
     */
    public void _testCohRemoveA(int tx) throws Exception {
        if (tx == TX_CONT) {
            // The transaction attribute of the remove method is TX_SUPPORT,
            // so the transaction cannot be initiate by the container
            fail("Transaction cannot be initiate by the container for this test");
        }
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        getAHome().remove("a0");
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // undo
        if (tx != TX_RB) {
            ARemote a0 = getAHome().create("a0");
            a0.assignBInNewTx("b0");
        }
        checkIsInitialState();
    }

    public void testCohRemoveATxNo() throws Exception {
        _testCohRemoveA(TX_NO);
    }

    public void testCohRemoveATxCall() throws Exception {
        _testCohRemoveA(TX_CALL);
    }

    public void testCohRemoveATxRb() throws Exception {
        _testCohRemoveA(TX_RB);
    }

    /**
     * Test of coherence b0.remove()
     */
    public void _testCohRemoveB(int tx) throws Exception {
        if (tx == TX_CONT) {
            // The transaction attribute of the remove method is TX_SUPPORT,
            // so the transaction cannot be initiate by the container
            fail("Transaction cannot be initiate by the container for this test");
        }
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        getBHome().remove("b0");
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // checking
        if (tx != TX_RB) {
            ARemote a0 = getAHome().findByPrimaryKey("a0");
            ARemote a1 = getAHome().findByPrimaryKey("a1");
            ARemote a2 = getAHome().findByPrimaryKey("a2");
            String idrela0 = a0.retrieveB();
            String idrela1 = a1.retrieveB();
            String idrela2 = a2.retrieveB();

            assertNull("Wrong not null relation a0, found: " + idrela0, idrela0);
            assertNull("Wrong not null relation a1, found: " + idrela1, idrela1);
            assertNull("Wrong not null relation a2, found: " + idrela2, idrela2);
            // undo
            getBHome().create("b0");
            a0.assignBInNewTx("b0");
            a1.assignBInNewTx("b0");
            a2.assignBInNewTx("b0");
        }
        checkIsInitialState();
    }

    public void testCohRemoveBTxNo() throws Exception {
        _testCohRemoveB(TX_NO);
    }

    public void testCohRemoveBTxCall() throws Exception {
        _testCohRemoveB(TX_CALL);
    }

    public void testCohRemoveBTxRb() throws Exception {
        _testCohRemoveB(TX_RB);
    }

    /**
     * Test of coherence b0.remove() => a0.retrieveB()=null && a1.retrieveB()=null && a2.retrieveB()=null
     * Same as _testCohRemove except that the called remove method is on the bean
     * instead of the home.
     */
    public void _testCohBeanRemoveB(int tx) throws Exception {
        if (tx == TX_CONT) {
            // The transaction attribute of the remove method is TX_SUPPORT,
            // so the transaction cannot be initiate by the container
            fail("Transaction cannot be initiate by the container for this test");
        }
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        BRemote b = getBHome().findByPrimaryKey("b0");
        b.remove();
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // checking
        if (tx != TX_RB) {
            ARemote a0 = getAHome().findByPrimaryKey("a0");
            ARemote a1 = getAHome().findByPrimaryKey("a1");
            ARemote a2 = getAHome().findByPrimaryKey("a2");
            String idrela0 = a0.retrieveB();
            String idrela1 = a1.retrieveB();
            String idrela2 = a2.retrieveB();

            assertNull("Wrong not null relation a0, found: " + idrela0, idrela0);
            assertNull("Wrong not null relation a1, found: " + idrela1, idrela1);
            assertNull("Wrong not null relation a2, found: " + idrela2, idrela2);
            // undo
            getBHome().create("b0");
            a0.assignBInNewTx("b0");
            a1.assignBInNewTx("b0");
            a2.assignBInNewTx("b0");
        }
        checkIsInitialState();
    }

    public void testCohBeanRemoveBTxNo() throws Exception {
        _testCohBeanRemoveB(TX_NO);
    }

    public void testCohBeanRemoveBTxCall() throws Exception {
        _testCohBeanRemoveB(TX_CALL);
    }

    public void testCohBeanRemoveBTxRb() throws Exception {
        _testCohBeanRemoveB(TX_RB);
    }

    public void testCohRemove2() throws Exception {
        _testCohRemoveB(TX_NO);
        _testCohRemoveB(TX_CALL);
        _testCohRemoveB(TX_NO);
        _testCohRemoveB(TX_RB);
    }

    /**
     * Test that the instances in the pool are correctly reused.
     * There was a bug because PName was not null for GEnClass at create.
     */
    public void testInstanceReuse1() throws Exception {

        ARemote a0 = getAHome().findByPrimaryKey("a0");
        ARemote a1 = getAHome().findByPrimaryKey("a1");
        ARemote a2 = getAHome().findByPrimaryKey("a2");
        ARemote a21 = getAHome().findByPrimaryKey("a21");

        //_testBasicSetEmpty(TX_RB);
        utx.begin();
        a1.assignB("b1");
        utx.rollback();

        //_testBasicSet(TX_RB);
        utx.begin();
        String bs = a21.retrieveB();
        a1.assignB(bs);
        utx.rollback();
        a1.retrieveB();
        a21.retrieveB();

        //_testCohRemoveB(TX_NO);
        getBHome().remove("b0");
        getBHome().create("b0");
        a0.assignBInNewTx("b0");

        //_testCohRemoveB(TX_CALL);
        utx.begin();
        getBHome().remove("b0");
        utx.commit();
        BRemote b0 = getBHome().create("b0");
        a0.assignBInNewTx("b0");

        //_testCohRemoveB(TX_RB);
        utx.begin();
        getBHome().remove("b0");
        utx.rollback();

        //_testCohBeanRemoveB(TX_NO);
        b0.remove();
        String idrela0 = a0.retrieveB();
        assertNull("Wrong not null relation a0, found: " + idrela0, idrela0);
        // undo
        getBHome().create("b0");
        a0.assignBInNewTx("b0");
        a1.assignBInNewTx("b0");
        a2.assignBInNewTx("b0");
        checkIsInitialState();
    }

    /**
     * Test that the instances in the pool are correctly reused.
     * There was a bug in jonas-3-0-beta0 because GenClass was
     * already initialized at create.
     */
    public void testInstanceReuse2() throws Exception {
        ARemote a4 = getAHome().findByPrimaryKey("a4");
        ARemote a5 = getAHome().findByPrimaryKey("a5");

        utx.begin();
        a5.assignB("b2");
        utx.rollback();

        getBHome().remove("b4");
        BRemote b4 = getBHome().create("b4");
        a4.assignB("b4");

        utx.begin();
        getBHome().remove("b4");
        utx.rollback();
        String s = a4.retrieveB();
        assertEquals("Broken relation", "b4", s);

        // remove b4 outside tx
        b4.remove();
        s = a4.retrieveB();
        assertNull("Wrong not null relation a4, found: " + s, s);
        // undo
        getBHome().create("b4");
        a4.assignB("b4");
        a5.assignB("b4");
        checkIsInitialState();
    }

    /**
     * This test did not work after optimization on lazy GenClass reading
     * this test is equivalent to :
     *   _testCohRemoveB(TX_RB)
     *   _testCohRemoveB(TX_NO)
     */
    public void testInstanceReuse3() throws Exception {
        String id;
        //_testCohRemoveB(TX_RB);
        utx.begin();
        getBHome().remove("b0");
        utx.rollback();
        //_testCohRemoveB(TX_NO);
        getBHome().remove("b0");
        // checking
        ARemote a0 = getAHome().findByPrimaryKey("a0");
        id = a0.retrieveB();
        assertNull("Wrong not null relation a0, found: " + id, id);
        ARemote a1 = getAHome().findByPrimaryKey("a1");
        id = a1.retrieveB();
        assertNull("Wrong not null relation a1, found: " + id, id);
        ARemote a2 = getAHome().findByPrimaryKey("a2");
        id = a2.retrieveB();
        assertNull("Wrong not null relation a2, found: " + id, id);
        // undo
        getBHome().create("b0");
        a0.assignBInNewTx("b0");
        a1.assignBInNewTx("b0");
        a2.assignBInNewTx("b0");
        checkIsInitialState();
    }

    public void testRollback() throws Exception {
        ARemote a = getAHome().findByPrimaryKey("a1");
        String orig = a.retrieveB();

        // disassociate and commit
        utx.begin();
        a.assignB(null);
        utx.commit();
        assertEquals(null, a.retrieveB());

        // revert to original state outside of a user transaction
        a.assignB(orig);

        // retrieveB inside a transaction
        utx.begin();
        assertEquals(orig, a.retrieveB());
        utx.rollback();

        // verify that retrieveB returns correct value after rollback
        try {
            assertEquals(orig, a.retrieveB());
        } finally {
            // force sync to cleanup
            sync(true);
        }
        checkIsInitialState();
    }

}
