package eu.dnetlib.efg1914.commons.dao;

import java.io.BufferedInputStream;
import java.io.InputStream;

import org.apache.log4j.Logger;

import eu.dnetlib.efg1914.commons.store.MediaStore;
import eu.dnetlib.efg1914.commons.store.MediaStoreException;

public class MediaFileDAO {

	private MediaStore mediaStore = null;
	private Logger logger = Logger.getLogger(MediaFileDAO.class);

	/**
	 * Saves a media file and returns the id
	 * 
	 * @param filetype
	 * @param fileBytes
	 * @return
	 * @throws DAOException
	 */

	public String save(String filetype, byte[] fileBytes) throws DAOException {
		String id = null;
		try {
			id = mediaStore.saveFileBytes(filetype, fileBytes);
			logger.debug("save media file with id.");

		} catch (Exception mse) {
			logger.error("Fail to save media dao.", mse);
			throw new DAOException("Fail to save media dao.", mse);
		}

		return id;
	}

	public String save(String filetype, BufferedInputStream filestream) throws DAOException {
		String id = null;
		try {
			id = mediaStore.saveFileStream(filetype, filestream);

		} catch (MediaStoreException mse) {
			logger.error("Fail to save media dao.", mse);
			throw new DAOException("Fail to save media dao.", mse);
		}

		return id;
	}

	public byte[] getById(String id) throws DAOException {
		try {
			return mediaStore.retrieveBytes(id);

		} catch (MediaStoreException mse) {
			logger.error("Fail to get dao with id " + id, mse);
			throw new DAOException("Fail to get dao with id " + id, mse);
		}
	}

	@Deprecated
	public InputStream getStreamById(String id) throws DAOException {
		try {
			return mediaStore.retrieveStream(id);

		} catch (MediaStoreException mse) {
			logger.error("Fail to get dao with id " + id, mse);
			throw new DAOException("Fail to get dao with id " + id, mse);
		}
	}

	public void delete(String id) throws DAOException {
		try {
			if ((id != null) && (!id.isEmpty())) {

				mediaStore.removeFile(id);
			}

		} catch (MediaStoreException mse) {
			logger.error("File does not exist in media store" + id);
			throw new DAOException("Fail to remove file with id: " + id + "File does not exist. ", mse);
		}

	}

	public MediaStore getMediaStore() {
		return mediaStore;
	}

	public void setMediaStore(MediaStore mediaStore) {
		this.mediaStore = mediaStore;
	}

	public void cleanUp() throws MediaStoreException {
		this.mediaStore.close();
	}

}
