package com.ffii.fhsmsc.modules.file.service;

import java.io.InputStream;
import java.util.Map;

import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.stereotype.Service;

import com.ffii.core.support.AbstractBaseEntityService;
import com.ffii.core.support.JdbcDao;
import com.ffii.fhsmsc.modules.file.entity.FileBlob;
import com.ffii.fhsmsc.modules.file.entity.FileBlobRepository;

@Service
public class FileBlobService extends AbstractBaseEntityService<FileBlob, Long, FileBlobRepository> {

	public FileBlobService(JdbcDao jdbcDao, FileBlobRepository repository) {
		super(jdbcDao, repository);
	}

	public Long saveOrUpdate(Long fileId, InputStream inputStream) {
		String sql = "INSERT INTO file_blob (fileId, bytes) VALUES (:fileId, :inputStream)";
		long rows = 0;
		try {
			rows = jdbcDao.executeUpdateAndReturnId(sql, Map.of("fileId", fileId, "inputStream", inputStream));
			inputStream.close();
		} catch (Exception e) {
			logger.info(ExceptionUtils.getStackTrace(e));
		}
		return rows;
	}

	public Long saveByRepository(FileBlob obj) {
		FileBlob temp = repository.save(obj);
		return temp.getId();
	}

	public Long findIdByFileId(Long fileId) {
		Map<String, Object> args = Map.of("fileId", fileId);
		return (long) jdbcDao.queryForInt("SELECT fb.id " +
				"FROM file_blob fb where fb.fileId = :fileId ", args);
	}
}
