package org.msh.etbm.services.gxalert;

import org.apache.commons.beanutils.PropertyUtils;
import org.jboss.seam.Component;
import org.jboss.seam.annotations.In;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Transactional;
import org.msh.etbm.rest.gxalert.GxalertForm;
import org.msh.tb.entities.GxalertData;
import org.msh.tb.entities.Workspace;

import javax.persistence.EntityManager;
import java.util.Date;
import java.util.List;

/**
 * Created by ricardo on 12/12/14.
 */
@Name("gxalertService")
public class GxalertService {

    @In
    EntityManager entityManager;

    /**
     * This service will try to find the form.uniqueId with any other registry on the database.
     * If it finds, this registry will be updated, if not, a new one will be created.
     * @param form
     * @return the id of the xalertdata created or updated
     * @throws Exception
     */
    @Transactional
    public Integer saveData(GxalertForm form) throws Exception {
        List<GxalertData> gxalertDataList = entityManager.createQuery("from GxalertData where uniqueId like :uniqueId")
                .setParameter("uniqueId", form.getUniqueId())
                .getResultList();

        GxalertData data = null;
        if (gxalertDataList == null || gxalertDataList.size() < 1) {
            data = new GxalertData();
        } else {
            data = gxalertDataList.get(0);
        }

        PropertyUtils.copyProperties(data, form);

        Workspace ws = (Workspace) Component.getInstance("defaultWorkspace");
        data.setWorkspace(ws);
        data.setRecordDate(new Date());

        entityManager.persist(data);
        entityManager.flush();

        return data.getId();
    }
}
