package common.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import common.log.Log;
import io.netty.util.CharsetUtil;

public class FileUtils {
	public static String read(InputStream input) throws IOException {
		return new String(readBytes(input), CharsetUtil.UTF_8);
	}

	public static byte[] readBytes(InputStream input) throws IOException {
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		byte[] buffer = new byte[4096];
		long count = 0L;
		int n;
		for(boolean u = false; -1 != (n = input.read(buffer)); count += (long)n) {
			output.write(buffer, 0, n);
		}
		return output.toByteArray();
	}

	public static String read(File file) throws IOException {
		FileInputStream in = null;
		String s;
		try {
			in = new FileInputStream(file);
			s = FileUtils.read(in);
		}
		finally {
			try {
				if(in != null)
					in.close();
			}
			catch(IOException e) {
			}
		}
		return s;
	}

	public static void write(File file, String data) throws IOException {
		FileOutputStream out = null;
		try {
			out = new FileOutputStream(file);
			if(out != null) {
				out.write(data.getBytes(CharsetUtil.UTF_8));
				out.close();
			}
		}
		finally {
			try {
				if(out != null)
					out.close();
			}
			catch(IOException e) {
			}
		}
	}
	
	public static InputStream getResource(String path) throws FileNotFoundException {
		InputStream in = FileUtils.class.getResourceAsStream("/" + path);
		if(in == null)
			throw new FileNotFoundException(path);
		return in;
	}

	public static boolean deleteFiles(File[] files) {
		if(files == null) {
			Log.JNI.warn("Konnte Ordner nicht löschen");
			return false;
		}
	
		for(int i = 0; i < files.length; ++i) {
			File file = files[i];
			Log.JNI.info("Lösche " + file);
	
			if(file.isDirectory() && !deleteFiles(file.listFiles())) {
				Log.JNI.warn("Konnte Ordner " + file + " nicht löschen");
				return false;
			}
	
			if(!file.delete()) {
				Log.JNI.warn("Konnte Datei " + file + " nicht löschen");
				return false;
			}
		}
	
		return true;
	}
}
