package org.richfaces.realworld.fileupload;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileTest {

	private String uploadRoot = "F:/Upload/";
	
	public String getUploadRoot() {
		return uploadRoot;
	}
	
	private String getFileSeparator() {
		return System.getProperty("file.separator");
	}

	public boolean isDirectoryPresent(String directory) {
		String fullPath = getAbsolutePath(directory);
		File file = new File(fullPath);
		return file.exists() && file.isDirectory();
	}

	public void deleteDirectory(String directory) {
		String fullPath = getAbsolutePath(directory);
		File file = new File(fullPath);
		if(file.exists()){
			for(String f :file.list()){
				File temp = new File(fullPath+getFileSeparator()+f);
				temp.delete();
			}
			file.delete();
		}
	}

	public void renameDirectory(String directoryOld, String directoryNew) throws Exception {
		String fullPath = getAbsolutePath(directoryOld);
		File fileOld = new File(fullPath);
		File fileNew = new File(getUploadRoot() + directoryNew);
		createDirectoryIfNotExist(directoryNew);
		if(fileNew.exists())
			if( fileNew.isDirectory() ){
				throw new Exception("exc");
			}else{
				fileNew.delete();
			}
		fileOld.renameTo(fileNew);
	}

	public void addDirectory(String directory) {
		String fullPath = getAbsolutePath(directory);
		File file = new File(fullPath);
		file.mkdirs();
	}

	public void addImage(String fileName, byte[] data) throws IOException {
		createDirectoryIfNotExist(fileName);
		FileOutputStream b = new FileOutputStream(getUploadRoot() + fileName);
		b.write(data);
		b.close();
	}

	public void deleteImage(String fileName) {
		String fullPath = getAbsolutePath(fileName);
		File file = new File(fullPath);
		if(file.exists()){
			file.delete();
		}
	}

	public void renameImage(String fileNameOld, String fileNameNew) {
		createDirectoryIfNotExist(fileNameNew);
		String fullPath = getAbsolutePath(fileNameOld);
		File fileOld = new File(fullPath);
		File fileNew = new File(getAbsolutePath(fileNameNew));
		if(fileNew.exists()){
			fileNew.delete();
		}
		fileOld.renameTo(fileNew);
	}

	private void createDirectoryIfNotExist(String fileNameNew) {
		int lastIndexOf = fileNameNew.lastIndexOf(getFileSeparator());
		if(lastIndexOf > 0){
			String directory = fileNameNew.substring(0, lastIndexOf);
			File file = new File(getUploadRoot()+directory);
			if(!file.exists()){
				file.mkdirs();
			}
		}
	}

	public boolean isImagePresent(String fileName) {
		String fullPath = getAbsolutePath(fileName);
		File file = new File(fullPath);
		return file.exists() && !file.isDirectory();
	}

	private String getAbsolutePath(String fileName) {
		return getUploadRoot() + fileName;
	}

}
