package info.bukova.isspst.storage;

import javax.servlet.ServletContext;
import java.io.*;

public class LocalFileStorage extends AbstractFileStorage<String>  {

	private String rootPath;
	private ServletContext context;

	public void setRootPath(String rootPath) {
		this.rootPath = rootPath;
	}

	@Override
	public String getRootPath() {
		return this.rootPath;
	}

	public void setContext(ServletContext ctx) {
		this.context = ctx;
	}

	private String getFullPath() {
		return context.getRealPath(rootPath) + File.separator;
	}

	@Override
	public void saveFile(byte[] data, String fileID) {
		saveFileDataToPath(data, getFullPath() + fileID);
	}

	public void saveFile(File file, String fileID) {
		saveFileToPtah(file, getFullPath() + fileID);
	}

	@Override
	public void removeFile(String fileID) {
		removeFileByPath(getFullPath() + fileID);
	}

	@Override
	public byte[] fileData(String fileID) {
		return fileDataFromPath(getFullPath() + fileID);
	}

	@Override
	public File file(String fileID) {
		return fileFromPath(getFullPath() + fileID);
	}

	@Override
	public void moveFile(String source, String destination) {
		saveFile(new File(getFullPath() + source), destination);
	}

	@Override
	public void createDirectory(String dir) {
		File f = new File(getFullPath() + dir);
		if (!f.mkdir()) {
			throw new StorageException("Cannot create directory: "
					+ getFullPath() + dir);
		}
	}

	@Override
	public boolean dirExists(String path) {
		File f = new File(getFullPath() + path);
		return f.exists() && f.isDirectory();
	}

	@Override
	public String serverPath(String fileID) {
		return context.getRealPath(rootPath + File.separator + fileID);
	}

}
