/*
 * 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.rmi.RemoteException;
import java.util.Collection;
import java.util.Iterator;
import javax.ejb.EJBObject;
import javax.ejb.FinderException;
import javax.ejb.RemoveException;
import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import junit.framework.Assert;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.objectweb.jonas.jtests.beans.relation.dass.DassHome;
import org.objectweb.jonas.jtests.beans.relation.dass.P1Remote;
import org.objectweb.jonas.jtests.beans.relation.dass.P1HomeRemote;
import org.objectweb.jonas.jtests.beans.relation.dass.P2Remote;
import org.objectweb.jonas.jtests.beans.relation.dass.P2HomeRemote;
import org.objectweb.jonas.jtests.beans.relation.dass.P3Remote;
import org.objectweb.jonas.jtests.beans.relation.dass.P3HomeRemote;
import org.objectweb.jonas.jtests.beans.relation.dass.P4Remote;
import org.objectweb.jonas.jtests.beans.relation.dass.P4HomeRemote;
import org.objectweb.jonas.jtests.beans.relation.dass.ARemote;
import org.objectweb.jonas.jtests.beans.relation.dass.AHomeRemote;
import org.objectweb.jonas.jtests.beans.relation.dass.BRemote;
import org.objectweb.jonas.jtests.beans.relation.dass.BHomeRemote;
import org.objectweb.jonas.jtests.util.JTestCase;

/**
 * This test suite tests specifics mapping used in some applications
 * for example, cmr field and cmp field mapped on the same table column
 * @author Philippe Durieux
 */
public class F_Dass extends JTestCase {

    /**
     * Reference on the remote Home's
     */
    private static P1HomeRemote p1home = null;
    private static P2HomeRemote p2home = null;
    private static P3HomeRemote p3home = null;
    private static P4HomeRemote p4home = null;
    private static AHomeRemote ahome = null;
    private static BHomeRemote bhome = null;

    /**
     * Standard constructor
     */
    public F_Dass(String name) {
        super(name);
    }

    protected boolean isInit = false;

    /**
     * setup is called before each test case.
     * If not initialized, load the dass bean and lookup the Home.
     */
    protected void setUp() {
        super.setUp();
        if (!isInit) {
            useBeans("dass", false);
            try {
                p1home = (P1HomeRemote) PortableRemoteObject.narrow(ictx.lookup("relation_dass_P1Home"),
                                                                    P1HomeRemote.class);
                p2home = (P2HomeRemote) PortableRemoteObject.narrow(ictx.lookup("relation_dass_P2Home"),
                                                                    P2HomeRemote.class);
                p3home = (P3HomeRemote) PortableRemoteObject.narrow(ictx.lookup("relation_dass_P3Home"),
                                                                    P3HomeRemote.class);
                p4home = (P4HomeRemote) PortableRemoteObject.narrow(ictx.lookup("relation_dass_P4Home"),
                                                                    P4HomeRemote.class);
                ahome = (AHomeRemote) PortableRemoteObject.narrow(ictx.lookup("relation_dass_AHome"),
                                                                  AHomeRemote.class);
                bhome = (BHomeRemote) PortableRemoteObject.narrow(ictx.lookup("relation_dass_BHome"),
                                                                  BHomeRemote.class);
            } catch (NamingException e) {
                fail("Cannot get bean home: " + e.getMessage());
            }
            isInit = true;
        }
    }

    /**
     * teardown is called after each test case.
     * Notes for debugging :
     * To see DataBase state after a test is passed :
     * Replace the cleanall() by sync(false).
     */
    protected void tearDown() throws Exception {
        cleanall();
        //sync(false);
    }

    /**
     * Cleanup all the dass after each test, to make tests independant.
     * Use transaction to avoid known bugs during cleanup.
     * (With no transaction -> 1 remove will fail)
     */
    private void cleanall() throws Exception {
        debug("remove all beans");

        // In case there is a problem during remove, we must unload
        // the bean to restart properly.
        try {
            cleanAllBeans(ahome);
            cleanAllBeans(bhome);
            cleanAllBeans(p1home);
            cleanAllBeans(p2home);
            cleanAllBeans(p3home);
            cleanAllBeans(p4home);
        } catch (Exception e) {
            error("Exception in cleanup: " + e);
            unloadBeans("dass");
            isInit = false;
        }
    }
        
    private void cleanAllBeans(DassHome home) throws RemoteException, RemoveException {
        try {
            Collection c = home.findAll();
            for (Iterator i = c.iterator(); i.hasNext(); ) {
                EJBObject p = (EJBObject) i.next();
                p.remove();
            }
        } catch (FinderException e) {
        }
    }

    // ---------------------------------------------------------------
    // Set of the tests that are passed automatically.
    // ---------------------------------------------------------------

    public void testCreateA() throws Exception {
        ahome.create("A1");
    }

    public void testCreateB() throws Exception {
        bhome.create("B1");
    }

    /**
     * This test fails, normally, because:
     * - setting the cmr field doesn't work because it's also a cmp field.
     * - the cmp field is not changed, so this means that the cmr field is readonly.
     * Jonas should throw an exception when we try to modify this kind of cmr field.
     */
    public void _testCreateA2B() throws Exception {
        ARemote a1 = ahome.create("A1");
        bhome.create("B1");
        a1.assignB("B1");
        String cmrval = a1.getBcmrvalue();
        assertTrue("Bad cmr value:" + cmrval, "B1".equals(cmrval));
    }

    public void _testCreateA2BTx() throws Exception {
        try {
            utx.begin();
            _testCreateA2B();
        } finally {
            try {
                utx.commit();
            } catch (Exception ii) {
            }
        }
    }

    /**
     * Simple example with 2 beans with the same pk and a cmr on this pk.
     * looks like a bean mapped on 2 tables.
     */
    public void testCreateP1P2() throws Exception {
        P1Remote p1 = p1home.create("P", "100");
        P2Remote p2 = p2home.create("P");
        String val = p2.getP1Value();
        assertTrue("Cannot access bean P1", "100".equals(val));
    }

    /**
     * Complex example of beans with cmr mapped on fields of the primary key.
     * Note that the primary key is composite.
     */
    public void testCreateP3() throws Exception {
        P1Remote p1 = p1home.create("P", "100");
        P4Remote p4 = p4home.create("P", "102");
        P3Remote p3 = p3home.create("P3", "P");
        String val = p3.getP1Value();
        assertTrue("Cannot access bean P1", "100".equals(val));
        val = p3.getP4Value();
        assertTrue("Cannot access bean P4", "102".equals(val));
    }

    /**
     * Run all the tests of this suite.
     */
    public static Test suite() {
        return new TestSuite(F_Dass.class);
    }

    public static void main(String args[]) throws Exception {
        String testtorun = null;
        
        // Get args
        for (int argn = 0; argn < args.length; argn++) {
            String sarg = args[argn];
            if (sarg.equals("-n")) {
                testtorun = args[++argn];
            }
        }
        if (testtorun == null) {
            junit.textui.TestRunner.run(suite());
        } else {
            junit.textui.TestRunner.run(new F_Dass(testtorun));
        }
    }

}
