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

/**
 * For testing many-to-one unidirectional relationships
 * @author S.Chassande-Barrioz, J. Camilleri
 *
 * This is an advanced test suite for home interface on entity bean CMP2.
 *
 **/
public class G_Relation_mouEC2 extends A_Cmp2Util {


    private static String BEAN_HOME_A = "relation_mou_AHome";
    protected static AHomeRemote ahome = null;
    private static String BEAN_HOME_B = "relation_mou_BHome";
    protected static BHomeRemote bhome = null;

    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 G_Relation_mouEC2(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);
                // 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) {
                    // Make the initialization needed for the tests
                    try {
                        utx.begin();
                        ARemote a0 = ahome.create("a0");
                        ARemote a1 = ahome.create("a1");
                        ARemote a2 = ahome.create("a2");
                        ARemote a3 = ahome.create("a3");
                        ARemote a4 = ahome.create("a4");
                        ARemote a5 = ahome.create("a5");
                        ARemote a20 = ahome.create("a20");
                        ARemote a21 = ahome.create("a21");
                        ARemote a22 = ahome.create("a22");
                        bhome.create("b0");
                        bhome.create("b1");
                        bhome.create("b2");
                        bhome.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 = ahome.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 = ahome.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);
    }
  
    /**
     * 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 = ahome.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);
    }

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

   

  

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

   
    /**
     * 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 = ahome.findByPrimaryKey("a1");
        ARemote a21 = ahome.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 = ahome.findByPrimaryKey("a0");
            ARemote a2 = ahome.findByPrimaryKey("a2");
            ARemote a3 = ahome.findByPrimaryKey("a3");
            ARemote a20 = ahome.findByPrimaryKey("a20");
            ARemote a22 = ahome.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();
    }

   

 

    /**
     * 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();
        }
        ahome.remove("a0");
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // undo
        if (tx != TX_RB) {
            ARemote a0 = ahome.create("a0");
            a0.assignBInNewTx("b0");
        }
        checkIsInitialState();
    }

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

}
