package org.msh.utils;

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.tb.application.TransactionManager;
import org.msh.tb.entities.DbCache;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;

/**
 * Created by mauri on 29/05/2017.
 */
@Name("dbCacheService")
public class DbCacheService {

    @In
    EntityManager entityManager;

    public void save(String hash, Object obj){

        if (hash == null || hash.isEmpty() || hash.length() != 32) {
            throw new RuntimeException("Hash is not valid");
        }

        if (obj == null) {
            throw new RuntimeException("Object can not be null");
        }

        // delete previous value for this hash
        entityManager.createQuery("delete from DbCache where hash like :hash")
                .setParameter("hash", hash)
                .executeUpdate();

        String objJson = JsonUtils.objectToJSONString(obj, false);

        DbCache dbCache = new DbCache();
        dbCache.setHash(hash);
        dbCache.setJson(objJson);

        // save cache
        entityManager.persist(dbCache);
    }

    public <T> T getCache(String hash, Class<T> type){

        if (hash == null || hash.isEmpty() || hash.length() != 32) {
            throw new RuntimeException("Hash is not valid");
        }

        String json;

        try {
            // get json
            json = (String) entityManager.createQuery("select json from DbCache where hash like :hash")
                    .setParameter("hash", hash)
                    .getSingleResult();
        } catch (NoResultException e) {
            return null;
        }

        if (json == null || json.isEmpty()) {
            return null;
        }

        return JsonUtils.parseString(json, type);
    }
}
