package com.fp.general.rules.query.code;

import java.sql.Timestamp;

import com.fp.dto.Response;
import com.fp.dto.query.QueryRequest;
import com.fp.dto.rules.QueryRule;
import com.fp.persistence.commondb.PersistenceHelper;
import com.fp.persistence.commondb.helper.FormatDates;
import com.fp.persistence.pgeneral.image.TgeneFilesDetail;
import com.fp.persistence.pgeneral.image.TgeneFilesDetailKey;

/**
 * Clase que devuelve en bytes un archivo
 *
 * @author scastillo
 */
public class DataBaseFile extends QueryRule {

    /**
     * Metodo que devuelve en forma de bytes un archivo
     *
     * @param pQueryRequest
     * @return
     * @throws Exception
     */
    @Override
    public QueryRequest process(QueryRequest pQueryRequest) throws Exception {
        Response response = pQueryRequest.getResponse();
        Integer code = (Integer) pQueryRequest.get("code");
        Timestamp dateto = null;
        if (pQueryRequest.get("dateto") != null) {
            dateto = Timestamp.valueOf((String) pQueryRequest.get("dateto"));
        } else {
            dateto = FormatDates.getDefaultExpiryTimestamp();
        }
        TgeneFilesDetailKey tgeneFilesDetailKey = new TgeneFilesDetailKey(code, dateto);
        TgeneFilesDetail tgeneFilesDetail = (TgeneFilesDetail) PersistenceHelper.getSession().get(TgeneFilesDetail.class, tgeneFilesDetailKey);
        if (tgeneFilesDetail != null) {
            response.put("file", tgeneFilesDetail.getImage());
            response.put("extension", tgeneFilesDetail.getExtension());
            response.put("contentType", tgeneFilesDetail.getContenttype());
            response.put("name", tgeneFilesDetail.getName());
        } else {
            response.put("file", null);
            response.put("extension", null);
            response.put("contentType", null);
            response.put("name", null);
        }
        return pQueryRequest;
    }
}
