package de.jottyfan.camporganizer.module.document;

import static de.jottyfan.camporganizer.db.jooq.Tables.T_DOCUMENT;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.jooq.DSLContext;
import org.jooq.SelectConditionStep;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import de.jottyfan.camporganizer.db.jooq.tables.records.TDocumentRecord;

/**
 *
 * @author jotty
 *
 */
@Repository
@Transactional(transactionManager = "transactionManager")
public class DocumentRepository {
	private static final Logger LOGGER = LogManager.getLogger(DocumentRepository.class);

	@Autowired
	private DSLContext jooq;

	/**
	 * get the document or null
	 *
	 * @param id the id of the document
	 * @return the download bean or null (if not found)
	 */
	public DownloadBean getDocument(Integer id) {
		SelectConditionStep<TDocumentRecord> sql = jooq
		// @formatter:off
			.selectFrom(T_DOCUMENT)
			.where(T_DOCUMENT.PK.eq(id));
		// @formatter:on
		LOGGER.trace(sql);
		TDocumentRecord r = sql.fetchOne();
		if (r == null) {
			return null;
		} else {
			DownloadBean bean = new DownloadBean();
			bean.setName(r.getName());
			bean.setFiletype(r.getFiletype());
			bean.setContent(r.getDocument());
			return bean;
		}
	}
}
