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

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

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

/**
 * This is an advanced test suite for home interface on entity bean CMP2.
 * Beans used: oob
 */
public class G_Relation_oobEC2 extends A_Cmp2Util {

    private static String BEAN_HOME_A = "relation_oob_AHome";
    private static String BEAN_HOME_B = "relation_oob_BHome";
    protected static AHomeRemote ahome = null;
    protected static BHomeRemote bhome = null;

   
    public G_Relation_oobEC2(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("oob", 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("a2");
                } catch (Exception e) {
                    // Make the initialization needed for the tests
                    try {
                        utx.begin();
                        ARemote a1 = ahome.create("a1");
                        ARemote a2 = ahome.create("a2");
                        ahome.create("a3");
                        bhome.create("b1");
                        bhome.create("b2");
                        bhome.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("oob");
            }
        }
    }

    /*
     * 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 = ahome.findByPrimaryKey("a1");
        BRemote b1 = bhome.findByPrimaryKey("b1");
        ARemote a2 = ahome.findByPrimaryKey("a2");
        BRemote b2 = bhome.findByPrimaryKey("b2");
        ARemote a3 = ahome.findByPrimaryKey("a3");
        BRemote b3 = bhome.findByPrimaryKey("b3");
        String idB1 = a1.retrieveB();
        String idB2 = a2.retrieveB();
        String idB3 = a3.retrieveB();
        String idA1 = b1.retrieveA();
        String idA2 = b2.retrieveA();
        String idA3 = b3.retrieveA();

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


    /**
     * 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 = ahome.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();
    }

   

    /**
     * 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 = ahome.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);
    }
   
    /**
     * 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 = ahome.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();
    }

   
    /**
     * test coherence relation one to one bidirectionnel,
     * A1.assignB(B2) => A1.retreiveB()=B2 && B2.retreiveA()=A1 && B1.retreiveA()=null && A2.retreiveB()=null
     */
    public void _testCohSetOne(int tx) throws Exception {
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a1 = ahome.findByPrimaryKey("a1");
        BRemote b1 = bhome.findByPrimaryKey("b1");
        ARemote a2 = ahome.findByPrimaryKey("a2");
        BRemote b2 = bhome.findByPrimaryKey("b2");
        ARemote a3 = ahome.findByPrimaryKey("a3");
        BRemote b3 = bhome.findByPrimaryKey("b3");
        // 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());
            assertNull("Bad coherence of relation null : expected for b1.retreiveA() found :" + b1.retrieveA(), b1.retrieveA());
            assertEquals("Bad coherence of relation a1 : expected for b2.retreiveA() found :" + b2.retrieveA(), "a1", b2.retrieveA());
            assertEquals("Bad coherence of relation b2 : expected for a1.retreiveB() found :" + a1.retrieveB(), "b2", a1.retrieveB());

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

   


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