/*
 * 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 junit.framework.Test;
import junit.framework.TestSuite;
import org.objectweb.jonas.jtests.beans.relation.s1pkcomp.AHomeRemote;
import org.objectweb.jonas.jtests.beans.relation.s1pkcomp.ARemote;
import org.objectweb.jonas.jtests.beans.relation.s1pkcomp.BHomeRemote;
import org.objectweb.jonas.jtests.beans.relation.s1pkcomp.BRemote;
import org.objectweb.jonas.jtests.beans.relation.s1pkcomp.PK;

import javax.naming.NamingException;
import javax.rmi.PortableRemoteObject;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.Hashtable;

/**
 * Test composite PK for CMP2 entity beans with relationships M-N
 * this test uses beans s1pkcomp/*
 * @author S.Chassande-Barrioz
 */
public class F_Relation_s1pkcompEC2 extends A_Cmp2Util {

    static Hashtable tbRelationA2B = new Hashtable();


    static {
        tbRelationA2B.put("a-0", new String[]{});
        tbRelationA2B.put("a-1", new String[]{"b-1", "b-2"});
        tbRelationA2B.put("a-2", new String[]{"b-1", "b-2", "b-3"});
        tbRelationA2B.put("a-3", new String[]{"b-2", "b-3", "b-4"});
        // Translate the String[] to a Collection of PK (Primary Key of the bean B)
        for (Enumeration ea = tbRelationA2B.keys(); ea.hasMoreElements();) {
            String aname = (String) (ea.nextElement());
            String[] tb = (String[]) tbRelationA2B.get(aname);
            ArrayList col = new ArrayList(tb.length);
            for (int i = 0; i < tb.length; i++) {
                PK bpk = new PK(getStringBeforeDash(tb[i]), getIntAfterDash(tb[i]));
                col.add(bpk);
            }
            tbRelationA2B.put(aname, col);
        }
    }

    static Hashtable tbRelationB2A = new Hashtable();

    static {
        tbRelationB2A.put("b-0", new String[]{});
        tbRelationB2A.put("b-1", new String[]{"a-1", "a-2"});
        tbRelationB2A.put("b-2", new String[]{"a-1", "a-2", "a-3"});
        tbRelationB2A.put("b-3", new String[]{"a-2", "a-3"});
        tbRelationB2A.put("b-4", new String[]{"a-3"});
        // Translate the String[] to a Collection of PK (Primary Key of the bean A)
        for (Enumeration eb = tbRelationB2A.keys(); eb.hasMoreElements();) {
            String bname = (String) (eb.nextElement());
            String[] tb = (String[]) tbRelationB2A.get(bname);
            ArrayList col = new ArrayList(tb.length);
            for (int i = 0; i < tb.length; i++) {
                PK apk = new PK(getStringBeforeDash(tb[i]), getIntAfterDash(tb[i]));
                col.add(apk);
            }
            tbRelationB2A.put(bname, col);
        }
    }

    private static String BEAN_HOME_A = "relation_s1pkcomp_AHome";
    protected static AHomeRemote ahome = null;
    private static String BEAN_HOME_B = "relation_s1pkcomp_BHome";
    protected static BHomeRemote bhome = null;


    public F_Relation_s1pkcompEC2(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("s1pkcomp", 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(new PK("a", 0));
                } catch (Exception e) {
                    try {
                        utx.begin();
                        ARemote a0 = ahome.create("a", 0);
                        ARemote a1 = ahome.create("a", 1);
                        ARemote a2 = ahome.create("a", 2);
                        ARemote a3 = ahome.create("a", 3);
                        bhome.create("b", 0);
                        bhome.create("b", 1);
                        bhome.create("b", 2);
                        bhome.create("b", 3);
                        bhome.create("b", 4);
                        a1.assignB((Collection) tbRelationA2B.get("a-1"));
                        a2.assignB((Collection) tbRelationA2B.get("a-2"));
                        a3.assignB((Collection) tbRelationA2B.get("a-3"));
                    } 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("s1pkcomp");
            }
        }
    }

    /*
     * 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();
        // Check relations A to B
        for (Enumeration ea = tbRelationA2B.keys(); ea.hasMoreElements();) {
            String aname = (String) (ea.nextElement());
            PK apk = new PK(getStringBeforeDash(aname), getIntAfterDash(aname));
            ARemote a = ahome.findByPrimaryKey(apk);
            Collection colActual = a.retrieveB();
            ArrayList colExpected = (ArrayList) (tbRelationA2B.get(aname));
            if (!isCollectionEqual(colExpected, colActual)) {
                isOk = false;
                msgerror = msgerror.append("Wrong relation for " + aname
                                           + " (expected:" + colExpected
                                           + ", found:" + colActual + ")");
            }
        }
        // Check Relations B to A
        for (Enumeration eb = tbRelationB2A.keys(); eb.hasMoreElements();) {
            String bname = (String) (eb.nextElement());
            PK bpk = new PK(getStringBeforeDash(bname), getIntAfterDash(bname));
            BRemote b = bhome.findByPrimaryKey(bpk);
            Collection colActual1 = b.retrieveA();
            ArrayList colExpected1 = (ArrayList) (tbRelationB2A.get(bname));
            if (!isCollectionEqual(colExpected1, colActual1)) {
                isOk = false;
                msgerror = msgerror.append("Wrong relation for " + bname
                                           + " (expected:" + colExpected1
                                           + ", found:" + colActual1 + ")");
            }
        }
        return isOk;
    }

    /**
     * Remove an element in a relation.
     */
    protected void tCohRemoveInRel(int tx) throws Exception {
        String bRemovedString = "b";
        int bRemovedInt = 4;
        if ((tx == TX_CALL) || (tx == TX_RB)) {
            utx.begin();
        }
        ARemote a = ahome.findByPrimaryKey(new PK("a", 3));
        if (tx == TX_CONT) {
            a.removeFromBInNewTx(new PK(bRemovedString, bRemovedInt));
        } else {
            a.removeFromB(new PK(bRemovedString, bRemovedInt));
        }
        if (tx == TX_CALL) {
            utx.commit();
        } else if (tx == TX_RB) {
            utx.rollback();
        }
        // checking
        Collection ca = a.retrieveB();
        BRemote b4 = bhome.findByPrimaryKey(new PK("b", 4));
        Collection cb4 = b4.retrieveA();
        if (tx != TX_RB) {
            assertEquals("Wrong relations size for a-3: ", 2, ca.size());
            assertEquals("Wrong relations size for b-4: ", 0, cb4.size());
        } else {
            assertEquals("Wrong relations size for a-3: ", 3, ca.size());
            assertEquals("Wrong relations size for b-4: ", 1, cb4.size());
        }
        // undo
        if (tx != TX_RB) {
            a.addInB(new PK(bRemovedString, bRemovedInt));
        }
        // check to initial state
        checkIsInitialState();

    }

    public void testCohRemoveInRelTxNo() throws Exception {
        tCohRemoveInRel(TX_NO);
    }

    public void testCohRemoveInRelTxCall() throws Exception {
        tCohRemoveInRel(TX_CALL);
    }

    public void testCohRemoveInRelTxCont() throws Exception {
        tCohRemoveInRel(TX_CONT);
    }

    public void testCohRemoveInRelTxRb() throws Exception {
        tCohRemoveInRel(TX_RB);
    }

    public static Test suite() {
        return new TestSuite(F_Relation_s1pkcompEC2.class);
    }

    public static void main(String args[]) {
        String testtorun = null;
        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_Relation_s1pkcompEC2(testtorun));
        }
    }


}
