package info.bukova.isspst.storage;

import java.io.*;

/**
 * Abstraktni třída pro práci se soubory.
 *
 * @author Pepa Rokos
 */
public abstract class AbstractFileStorage<T> implements FileStorage<T> {

	protected void saveFileDataToPath(byte[] data, String path) {

		File file = new File(path);
		FileOutputStream os = null;
		try {
			os = new FileOutputStream(file);
			os.write(data);
			os.flush();
			os.close();
		} catch (FileNotFoundException e) {
			throw new StorageException("File cannot be found: " + file.getName(), e.getCause());
		} catch (IOException e) {
			throw new StorageException("Cannot write file: " + file.getName(), e.getCause());
		} finally {
			try {
				if (os != null) {
					os.flush();
					os.close();
				}
			} catch (IOException e) {
				throw new StorageException("Cannot close stream", e.getCause());
			}
		}
	}

	protected void saveFileToPtah(File file, String path) {
		File dest = new File(path + File.pathSeparator + file.getName());
		FileOutputStream fos = null;

		try {
			fos = new FileOutputStream(dest);
			fos.write(readFile(file));
			fos.flush();
			fos.close();
		} catch (FileNotFoundException e) {
			throw new StorageException("Cannot move file: " + file.getName(), e.getCause());
		} catch (IOException e) {
			throw new StorageException("Cannot move file: " + file.getName(), e.getCause());
		} finally {
			if (fos != null) {
				try {
					fos.flush();
					fos.close();
				} catch (IOException e) {
					throw new StorageException("Cannot close stream", e.getCause());
				}
			}
		}
	}

	protected void removeFileByPath(String path) {
		File f = new File(path);
		if (!f.delete()) {
			throw new StorageException("Cannot delete file: " + path);
		}
	}

	protected byte[] fileDataFromPath(String path) {
		File f = new File(path);
		return readFile(f);
	}

	protected byte[] readFile(File file) {
		byte[] out = new byte[(int) file.length()];

		FileInputStream fis = null;
		try {
			fis = new FileInputStream(file);
			fis.read(out);
			fis.close();
		} catch (FileNotFoundException e) {
			throw new StorageException("File cannot be found: " + file.getName(), e.getCause());
		} catch (IOException e) {
			throw new StorageException("Cannot read file: " + file.getName(), e.getCause());
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					throw new StorageException("Cannot close stream", e.getCause());
				}
			}
		}

		return out;
	}

	protected File fileFromPath(String path) {
		return new File(path);
	}

}
