package com.smartgwt.sample;

import com.isomorphic.base.Config;
import com.isomorphic.base.ISCInit;
import com.isomorphic.datasource.DSRequest;
import com.isomorphic.datasource.DSResponse;
import com.smartgwt.sample.server.dataModel.Applicant;
import com.smartgwt.sample.server.dataModel.PriceModel;
import org.junit.Assert;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by sboclinville on 02/11/2015.
 */
public class ApplicantDMITest {

    private Long applicantId;

    @BeforeClass
    public static void beforeClass() {
        // your webRoot folder shall contains the "AVRS_js" folder inside.
        String webRoot = "C:\\Dev\\IntelliJWorkspace\\GwtSample\\out\\artifacts\\SmartGwtSample";

        Config myConfig = Config.getGlobal();
        myConfig.put("webRoot", webRoot);

        ISCInit.go();
    }

    @Before
    public void initData() {
        EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("ds", new HashMap<String, Object>());
        EntityManager em = entityManagerFactory.createEntityManager();
        //delete content
        deleteApplicant(em);
        applicantId = createApplicant(em, "testJob");
    }

    public static void deleteApplicant(EntityManager em) {
        em.getTransaction().begin();
        em.createNativeQuery("DELETE FROM T_INVOICE").executeUpdate();
        em.createNativeQuery("DELETE FROM T_APPLICANT").executeUpdate();
        em.createNativeQuery("DELETE FROM T_PRICEMODEL").executeUpdate();
        em.getTransaction().commit();
    }

    private Long createApplicant(EntityManager em, String testJob) {
        em.getTransaction().begin();
        PriceModel pm = new PriceModel();
        pm.setPriceModelName("Test Price model");
        em.persist(pm);
        Applicant applicant = new Applicant();
        applicant.setJobNumber(testJob);
        applicant.setPriceModel(pm);
        em.persist(applicant);

        em.getTransaction().commit();
        return applicant.getId();
    }

    @Test
    public void testRequest() throws Exception {
        DSRequest dsRequest = new DSRequest("applicant", "update");

        String newName = "Wiii";
        dsRequest.setCriteria("id", applicantId);
        dsRequest.setFieldValue("name", newName);

        DSResponse dsResponse = dsRequest.execute();
        Applicant applicant = ((Applicant) ((ArrayList) dsResponse.getData()).get(0));

        Assert.assertEquals(newName, applicant.getName());
    }

}
