package dst.ass1.jpa.tests;

import static org.hamcrest.CoreMatchers.hasItems;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.Assert.assertTrue;

import java.util.Map;

import javax.persistence.EntityManager;

import org.junit.Rule;
import org.junit.Test;

import dst.ass1.jpa.ORMService;
import dst.ass1.jpa.model.IMetadata;
import dst.ass1.jpa.util.Constants;

/**
 * Tests that IMetadata is persisted correctly.
 */
public class Ass1_1_1_06Test {

    @Rule
    public ORMService orm = new ORMService();

    @Test
    public void testMetadataMap() {
        IMetadata md1 = orm.getModelFactory().createMetadata();

        md1.putData("key1", "value1");
        md1.putData("key2", "value2");

        EntityManager em = orm.getEntityManager();
        em.getTransaction().begin();

        em.persist(md1);
        em.flush();
        em.getTransaction().commit();

        EntityManager em2 = orm.createEntityManager();
        IMetadata md2 = em2.find(md1.getClass(), md1.getId());

        Map<String, String> map = md2.getData();

        assertThat(map.size(), is(2));
        assertThat(map.keySet(), hasItems("key1", "key2"));
        assertThat(map.get("key1"), is("value1"));
        assertThat(map.get("key2"), is("value2"));
    }

    @Test
    public void testMetadataMapJdbc() {
        assertTrue(orm.getDatabaseGateway().isTable(Constants.T_METADATA));
        assertTrue(orm.getDatabaseGateway().isTable(Constants.J_METADATA_DATA));
        assertTrue(orm.getDatabaseGateway().isColumnInTable(Constants.J_METADATA_DATA, Constants.I_METADATA));
        assertTrue(orm.getDatabaseGateway().isColumnInTable(Constants.J_METADATA_DATA, Constants.M_METADATA_DATA + "_KEY"));
    }

}
