/*******************************************************************************
 * Copyright (c) 1998, 2009 Oracle. All rights reserved.
 * This program and the accompanying materials are made available under the 
 * terms of the Eclipse Public License v1.0 and Eclipse Distribution License v. 1.0 
 * which accompanies this distribution. 
 * The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html
 * and the Eclipse Distribution License is available at 
 * http://www.eclipse.org/org/documents/edl-v10.php.
 *
 * Contributors:
 *     dclarke - Dynamic Persistence INCUBATION - Enhancement 200045
 *               http://wiki.eclipse.org/EclipseLink/Development/Dynamic
 *     mnorman - tweaks to work from Ant command-line,
 *               get database properties from System, etc.
 *     
 * This code is being developed under INCUBATION and is not currently included 
 * in the automated EclipseLink build. The API in this code may change, or 
 * may never be included in the product. Please provide feedback through mailing 
 * lists or the bug database.
 ******************************************************************************/
package org.eclipse.persistence.testing.tests.jpa.dynamic.simple;

//javase imports
import java.util.Calendar;

//java eXtensions
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

//JUnit4 imports
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assume.assumeTrue;

//EclipseLink imports
import org.eclipse.persistence.descriptors.ClassDescriptor;
import org.eclipse.persistence.dynamic.DynamicClassLoader;
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.eclipse.persistence.dynamic.DynamicType;
import org.eclipse.persistence.dynamic.DynamicTypeBuilder;
import org.eclipse.persistence.internal.dynamic.DynamicTypeImpl;
import org.eclipse.persistence.jpa.JpaHelper;
import org.eclipse.persistence.jpa.dynamic.JPADynamicHelper;
import org.eclipse.persistence.jpa.dynamic.JPADynamicTypeBuilder;
import org.eclipse.persistence.sessions.IdentityMapAccessor;
import org.eclipse.persistence.sessions.server.Server;

//domain-specific (testing) imports
import org.eclipse.persistence.testing.tests.jpa.dynamic.DynamicTestHelper;
import static org.eclipse.persistence.testing.tests.jpa.dynamic.DynamicTestHelper.DYNAMIC_PERSISTENCE_NAME;

public class SimpleTypeTestSuite {

    //test fixtures
    static EntityManagerFactory emf = null;
    static JPADynamicHelper helper = null;
    static DynamicType simpleType = null;
    
    @BeforeClass
    public static void setUp() throws Exception {
        emf = DynamicTestHelper.createEMF(DYNAMIC_PERSISTENCE_NAME);
        boolean isMySQL = JpaHelper.getServerSession(emf).getDatasourcePlatform().
            getClass().getName().contains("MySQLPlatform");
        assumeTrue(isMySQL);
        helper = new JPADynamicHelper(emf);
        DynamicClassLoader dcl = helper.getDynamicClassLoader();
        Class<?> javaType = dcl.createDynamicClass("model.Simple");
        DynamicTypeBuilder typeBuilder = new JPADynamicTypeBuilder(javaType, null, "SIMPLE_TYPE");
        typeBuilder.setPrimaryKeyFields("SID");
        typeBuilder.addDirectMapping("id", int.class, "SID");
        typeBuilder.addDirectMapping("value1", String.class, "VAL_1");
        typeBuilder.addDirectMapping("value2", boolean.class, "VAL_2");
        typeBuilder.addDirectMapping("value3", Calendar.class, "VAL_3");
        typeBuilder.addDirectMapping("value4", Character.class, "VAL_4");

        helper.addTypes(true, true, typeBuilder.getType());
        simpleType = helper.getType("Simple");
    }

    @AfterClass
    public static void tearDown() throws Exception {
        if (emf != null && emf.isOpen()) {
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();
            em.createNativeQuery("DROP TABLE SIMPLE_TYPE").executeUpdate();
            em.getTransaction().commit();
            em.close();
            emf.close();
        }
    }

    @Before
    @After
    public void clearSimpleTypeInstances() {
        if (emf != null && emf.isOpen()) {
            EntityManager em = emf.createEntityManager();
            em.getTransaction().begin();
            em.createQuery("DELETE FROM Simple").executeUpdate();
            em.getTransaction().commit();
            em.close();
        }
        JpaHelper.getServerSession(emf).getIdentityMapAccessor().initializeAllIdentityMaps();
    }
    
    @Test
    public void verifyConfig() throws Exception {
        ClassDescriptor descriptor = helper.getSession().getClassDescriptorForAlias("Simple");
        assertNotNull("No descriptor found for alias='Simple'", descriptor);
        DynamicTypeImpl simpleTypeImpl = (DynamicTypeImpl)simpleType;
        assertNotNull("'Simple' EntityType not found", simpleTypeImpl);
        assertEquals(1 + descriptor.getPrimaryKeyFields().size(), 
            simpleTypeImpl.getMappingsRequiringInitialization().size());
        assertEquals(descriptor, simpleTypeImpl.getDescriptor());
    }

    @Test
    public void find() {
        createSimpleInstance(1);
        EntityManager em = emf.createEntityManager();
        DynamicEntity simpleInstance = find(em, 1);
        assertNotNull("Could not find simple instance with id = 1", simpleInstance);
        simpleInstance = find(em, new Integer(1));
        assertNotNull("Could not find simple instance with id = Integer(1)", simpleInstance);
    }

    @Test
    public void simpleInstance_CRUD() {
        Server session = JpaHelper.getServerSession(emf);
        IdentityMapAccessor cache = session.getIdentityMapAccessor();
        DynamicEntity simpleInstance = createSimpleInstance(1);
        assertNotNull(simpleInstance);
        assertTrue(cache.containsObjectInIdentityMap(simpleInstance));
        cache.initializeAllIdentityMaps();
        assertFalse(cache.containsObjectInIdentityMap(simpleInstance));
        EntityManager em = emf.createEntityManager();
        assertFalse(em.contains(simpleInstance));
        simpleInstance = (DynamicEntity) em.merge(simpleInstance);
        assertTrue(em.contains(simpleInstance));
        em.close();
    }

    @Test
    public void verifyDefaultValuesFromEntityType() throws Exception {
        assertNotNull(simpleType);
        DynamicEntity simpleInstance = simpleType.newDynamicEntity();
        assertDefaultValues(simpleInstance);
    }

    @Test
    public void verifyDefaultValuesFromDescriptor() throws Exception {
        DynamicTypeImpl simpleTypeImpl = (DynamicTypeImpl)simpleType;
        assertNotNull(simpleTypeImpl);
        DynamicEntity simpleInstance = 
            (DynamicEntity)simpleTypeImpl.getDescriptor().getObjectBuilder().buildNewInstance();
        assertDefaultValues(simpleInstance);
    }

    protected void assertDefaultValues(DynamicEntity simpleInstance) {
        assertNotNull(simpleInstance);
        assertTrue("id not set on new instance", simpleInstance.isSet("id"));
        assertEquals("id not default value", 0, simpleInstance.get("id"));
        assertFalse("value1  set on new instance", simpleInstance.isSet("value1"));
        assertTrue("value2 not set on new instance", simpleInstance.isSet("value2"));
        assertEquals("value2 not default value", false, simpleInstance.get("value2"));
        assertFalse("value3 set on new instance", simpleInstance.isSet("value3"));
        assertFalse("value4  set on new instance", simpleInstance.isSet("value4"));
    }

    public DynamicEntity createSimpleInstance(int id) {
        EntityManager em = emf.createEntityManager();
        assertNotNull(simpleType);
        DynamicEntity simpleInstance = simpleType.newDynamicEntity();
        simpleInstance.set("id", id);
        simpleInstance.set("value2", true);
        assertEquals(0, ((Number) em.createQuery("SELECT COUNT(s) FROM Simple s").getSingleResult()).intValue());
        em.getTransaction().begin();
        em.persist(simpleInstance);
        em.getTransaction().commit();
        assertEquals(1, ((Number) em.createQuery("SELECT COUNT(s) FROM Simple s").getSingleResult()).intValue());
        DynamicEntity foundEntity = find(em, 1);
        assertNotNull(foundEntity);
        assertEquals(simpleInstance.get("id"), foundEntity.get("id"));
        assertEquals(simpleInstance.get("value1"), foundEntity.get("value1"));
        assertEquals(simpleInstance.get("value2"), foundEntity.get("value2"));
        em.close();
        return simpleInstance;
    }

    protected DynamicEntity find(EntityManager em, Object id) {
        return em.<DynamicEntity>find((Class<DynamicEntity>)simpleType.getJavaClass(), id);
    }
}