/*
 * 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 javax.ejb.ObjectNotFoundException;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;

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

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

/**
 * This is an advanced test suite for home interface on entity bean CMP2.
 */
public abstract class A_oou extends A_Cmp2Util {

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

    public A_oou(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("oou", false);
                // check if tables have been initialized
                try {
                    getAHome().findByPrimaryKey("a2");
                } catch (Exception e) {
                    // Make the initialization needed for the tests
                    try {
                        utx.begin();
                        ARemote a1 = getAHome().create("a1");
                        ARemote a2 = getAHome().create("a2");
                        getAHome().create("a3");
                        getBHome().create("b1");
                        getBHome().create("b2");
                        getBHome().create("b3");
                        a1.assignB("b1");
                        a2.assignB("b2");
                    } 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("oou");
            }
        }
    }


    /*
     * 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();

        ARemote a1 = getAHome().findByPrimaryKey("a1");
        BRemote b1 = getBHome().findByPrimaryKey("b1");
        ARemote a2 = getAHome().findByPrimaryKey("a2");
        BRemote b2 = getBHome().findByPrimaryKey("b2");
        ARemote a3 = getAHome().findByPrimaryKey("a3");
        BRemote b3 = getBHome().findByPrimaryKey("b3");
        String idB1 = a1.retrieveB();
        String idB2 = a2.retrieveB();
        String idB3 = a3.retrieveB();

        if (idB1!=null && !idB1.equals("b1")){
            isOk = false;
            msgerror.append("Wrong relation for  a1->b1"
                            +"(expected: A1.retrieveB()='b1'"
                            + ", found:" + idB1 + ")");
        }
        else if (idB2!=null && !idB2.equals("b2")){
            isOk = false;
            msgerror.append("Wrong relation for  a2->b2"
                            +"(expected: A2.retrieveB()='b2'"
                            + ", found:" + idB2 + ")");
        }
        else if (idB3!=null){
            isOk = false;
            msgerror.append("Wrong relation for  b3->a3"
                            +"(expected: B3.retrieveA()=null"
                            + ", found:" + idB3 + ")");
        }
        return isOk;
    }

    /**
     * Test inactivityTimeout with CMR fields
     */
    public void testInactivityCMR() throws Exception {
        ARemote a1 = getAHome().findByPrimaryKey("a1");
        sleep(6000);
        a1.retrieveB();
    }
    
    /**
     * Check that the bean 'a3' has no relation.
     */
    public void _testBasicGetEmpty(int tx) throws Exception {
        String  idB = null;
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a = getAHome().findByPrimaryKey("a3");
        if (tx == TX_CONT) {
            idB = a.retrieveBInNewTx();
        } else {
            idB = 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);
    }

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

    /**
     * Set a relation to empty : a3.assignB(null)
     */
    public void _testBasicSetEmptyNull(int tx) throws Exception {
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a = getAHome().findByPrimaryKey("a1");
        if (tx == TX_CONT) {
            a.assignBInNewTx(null);
        } else {
            a.assignB(null);
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // checking
        String idB = a.retrieveB();
        if (tx == TX_RB) {
            assertEquals("Wrong assign null for relation a1->b1: ","b1", idB);
        } else {
            assertNull("Wrong assign null for relation a1->b1: " + idB, idB);
        }
        // undo
        if (tx != TX_RB) {
            a.assignB("b1");
        }

        checkIsInitialState();

    }

    public void testBasicSetEmptyNullTxNo() throws Exception {
        _testBasicSetEmptyNull(TX_NO);
    }
    public void testBasicSetEmptyNullTxCall() throws Exception {
        _testBasicSetEmptyNull(TX_CALL);
    }
    public void testBasicSetEmptyNullTxCont() throws Exception {
        _testBasicSetEmptyNull(TX_CONT);
    }
    public void testBasicSetEmptyNullTxRb() throws Exception {
        _testBasicSetEmptyNull(TX_RB);
    }

    /**
     * test coherence relation one to one bidirectionnel,
     * A1.assignB(B2) => A1.retreiveB()=B2 && A2.retreiveB()=null
     */
    public void _testCohSetOne(int tx) throws Exception {

        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a1 = getAHome().findByPrimaryKey("a1");
        ARemote a2 = getAHome().findByPrimaryKey("a2");
        // change the relation
        if (tx == TX_CONT) {
            a1.assignBInNewTx("b2");
        } else {
            a1.assignB("b2");
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        if (tx != TX_RB) {
            // Verify expected result
            assertNull("Bad coherence of relation null : expected for a2.retreiveB() found :" + a2.retrieveB(), a2.retrieveB());
            assertEquals("Bad coherence of relation b2 : expected for a1.retreiveB() found :" + a1.retrieveB(), "b2", a1.retrieveB());

            // undo
            a2.assignB("b2");
            a1.assignB("b1");
        }
        checkIsInitialState();
    }

    public void testCohSetOneTxNo() throws Exception {
        _testCohSetOne(TX_NO);
    }
    public void testCohSetOneTxCall() throws Exception {
        _testCohSetOne(TX_CALL);
    }

    public void testCohSetOneTxCont() throws Exception {
        _testCohSetOne(TX_CONT);
    }

    public void testCohSetOneTxRb() throws Exception {
        _testCohSetOne(TX_RB);
    }

    /**
     * test coherence relation one to one bidirectionnel,
     * A3.assignB(B3)=>A3.retreiveB()==B3
     */
    public void _testCohWithoutRelation(int tx) throws Exception {

        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a3 = getAHome().findByPrimaryKey("a3");
        // change the relation
        if (tx == TX_CONT) {
            a3.assignBInNewTx("b3");
        } else {
            a3.assignB("b3");
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        if (tx != TX_RB) {
            // Verify expected result
            assertEquals("Bad coherence of relation : b3 expected for a3.retreiveB() found :"+a3.retrieveB(),"b3", a3.retrieveB());

            // undo
            a3.assignB(null);
        }
        checkIsInitialState();
    }

    public void testBasicCohWithoutRelation() throws Exception {
        _testCohWithoutRelation(TX_NO);
    }
    public void testBasicCohWithoutRelationTxCall() throws Exception {
        _testCohWithoutRelation(TX_CALL);
    }

    /**
     * test coherence relation one to one bidirectionnel,
     * A1.assignB(B3)=>A1.retreiveB()==B3
     */
    public void _testCohAlreadyAssign(int tx) throws Exception {

        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a1 = getAHome().findByPrimaryKey("a1");
        // change the relation
        if (tx == TX_CONT) {
            a1.assignBInNewTx("b3");
        } else {
            a1.assignB("b3");
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        if (tx != TX_RB) {
            // Verify expected result
            assertEquals("Bad coherence of relation : b3 expected for a1.retreiveB() found :"+a1.retrieveB(),"b3", a1.retrieveB());

            // undo
            a1.assignB("b1");
        }
        checkIsInitialState();
    }

    public void testCohAlreadyAssign() throws Exception {
        _testCohAlreadyAssign(TX_NO);
    }
    public void testCohAlreadyAssignTxCall() throws Exception {
        _testCohAlreadyAssign(TX_CALL);
    }

    /**
     * test coherence relation one to one bidirectionnel,
     * A1.assignB(null)=>A1.retreiveB()==null
     */
    public void _testCohSetNull(int tx) throws Exception {

        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a1 = getAHome().findByPrimaryKey("a1");
        // change the relation
        if (tx == TX_CONT) {
            a1.assignBInNewTx(null);
        } else {
            a1.assignB(null);
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        if (tx != TX_RB) {
            // Verify expected result
            assertNull("Bad coherence of relation : null expected for a1.retreiveB() found :"+a1.retrieveB(), a1.retrieveB());

            // undo
            a1.assignB("b1");
        }
        checkIsInitialState();
    }

    public void testCohSetNull() throws Exception {
        _testCohSetNull(TX_NO);
    }
    public void testCohSetNullTxCall() throws Exception {
        _testCohSetNull(TX_CALL);
    }


    /**
     * test coherence relation one to one bidirectionnel,
     * getBHome().remove(b1)=>B1 removed && A1.retreiveB()==null
     */
    public void _testCohRemove(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();
        }
        ARemote a1 = getAHome().findByPrimaryKey("a1");
        try {
            // remove the bean
            getBHome().remove("b1");
        } finally {
            if (tx == TX_CALL) {
                utx.commit();
            } else if (tx == TX_RB) {
                utx.rollback();
            }
        }
        if (tx != TX_RB) {
            // Verify expected result
            assertNull("Bad coherence of relation : null expected for a1.retreiveB() found :"+a1.retrieveB(), a1.retrieveB());
            try {
                BRemote b1 = getBHome().findByPrimaryKey("b1");
                fail("BA is not removed");
            } catch (ObjectNotFoundException e) {
            }

            // undo
            getBHome().create("b1");
            a1.assignB("b1");
        }
        checkIsInitialState();
    }

    public void testCohRemoveNoTx() throws Exception {
        _testCohRemove(TX_NO);
    }
    public void testCohRemoveTxCall() throws Exception {
        _testCohRemove(TX_CALL);
    }
    public void testCohRemoveTxRb() throws Exception {
        _testCohRemove(TX_RB);
    }

    public void testRemoveCreate() throws Exception {
        ARemote a1 = getAHome().findByPrimaryKey("a1");
        getBHome().remove("b1");
        BRemote b1 = null;
        try {
            b1 = getBHome().findByPrimaryKey("b1");
            fail("BA is not removed");
        } catch (ObjectNotFoundException e) {
        }

        // undo
        getBHome().create("b1");

        utx.begin();
        try {
            // remove the bean
            getBHome().remove("b1");
        } finally {
            utx.commit();
        }
        try {
            b1 = getBHome().findByPrimaryKey("b1");
            fail("BA is not removed");
        } catch (ObjectNotFoundException e) {
        }

        // undo
        b1 = getBHome().create("b1");
        a1.assignB("b1");

        // check initial state
        //ARemote a2 = getAHome().findByPrimaryKey("a2");
        BRemote b2 = getBHome().findByPrimaryKey("b2");
        try {
            String idB1 = a1.retrieveB();
        } catch (Exception e) {
            fail("a1.retrieveB():" + e);
        }

    }


    /**
     * test coherence relation one to one bidirectionnel,
     * B1.remove=>B1 removed && A1.retrieveB()==null
     * Same as _testCohRemove except that the called remove method is on the bean
     * instead of the home.
     */
    public void _testCohBeanRemove(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();
        }
        ARemote a1 = getAHome().findByPrimaryKey("a1");
        BRemote b1 = getBHome().findByPrimaryKey("b1");
        try {
            // remove the bean
            b1.remove();
        } finally {
            if (tx == TX_CALL) {
                utx.commit();
            } else if (tx == TX_RB) {
                utx.rollback();
            }
        }
        if (tx != TX_RB) {
            // Verify expected result
            assertNull("Bad coherence of relation : null expected for a1.retreiveB() found :"+a1.retrieveB(), a1.retrieveB());
            boolean not_found=false;
            try {
                b1 = getBHome().findByPrimaryKey("b1");
            } catch (ObjectNotFoundException e) {
                not_found=true;
            }
            assertTrue("BA is not removed",not_found);
            // undo
            getBHome().create("b1");
            a1.assignB("b1");
        }
        checkIsInitialState();
    }

    public void testCohBeanRemoveNoTx() throws Exception {
        _testCohBeanRemove(TX_NO);
    }
    public void testCohBeanRemoveTxCall() throws Exception {
        _testCohBeanRemove(TX_CALL);
    }
    public void testCohBeanRemoveTxRb() throws Exception {
        _testCohBeanRemove(TX_RB);
    }

    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();
    }

}

