package hc.adlrunner;

import hc.adl.IFunctionCallback;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Vector;

/**
 * Simple class to expose file operations to ADL
 * 
 * @author root
 * 
 */
public class ADLFile implements IFunctionCallback {
	private File file;

	private FileReader reader = null;

	private FileWriter writer = null;

	private Map<String, ADLFileFunctions> functions = new HashMap<String, ADLFileFunctions>();

	public ADLFile(String fileName) {
		file = new File(fileName);

		fillFunctionMap();
	}

	private void fillFunctionMap() {
		functions.put("close", ADLFileFunctions.close);
		functions.put("flush", ADLFileFunctions.flush);
		functions.put("read", ADLFileFunctions.read);
		functions.put("write", ADLFileFunctions.write);
	}

	public Object FunctionCallback(String funcName, Vector<Object> vParams) {
		ADLFileFunctions function = functions.get(funcName);
		if (function == null) {
			return null;
		}
		switch (function) {
		case close:
			if (writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					return false;
				}
			}
			return true;
		case flush:
			if (writer != null) {
				try {
					writer.flush();
				} catch (IOException e) {
					return false;
				}
			}
			return true;
		case read:
			if (reader == null) {
				try {
					reader = new FileReader(file);
				} catch (FileNotFoundException e) {
					return false;
				}
			}
			int len;
			if (vParams.size() < 1) {
				len = (int) file.length();
			} else {
				len = (Integer) vParams.get(0);
			}
			char[] buf = new char[len];
			try {
				reader.read(buf);
			} catch (IOException e) {
				return false;
			}
			return new String(buf);
		case write:
			if (writer == null) {
				try {
					writer = new FileWriter(file);
				} catch (IOException e) {
					return false;
				}
			}
			try {
				writer.write((String) vParams.get(0));
			} catch (IOException e) {
				return false;
			}
			return true;

		}
		return null;
	}
}
