package compbio.stat.collector;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

import org.apache.log4j.Logger;

import compbio.util.FileUtil;
import compbio.util.Util;
import compbio.ws.client.WSTester;

public class InputFilter {

	private static final Logger log = Logger.getLogger(InputFilter.class);

	/**
	 * Accepts input as valid unless it is a test input
	 * 
	 * @param input
	 * @return
	 */
	static boolean accept(File input) {
		if (input == null)
			return true;
		assert input.isFile() : "Input file is not a file! " + input;
		String[] fastainput = WSTester.fastaInput2records.split("\n");
		assert fastainput.length == 4;
		String[] aligninput = WSTester.fastaAlignment.split("\n");
		assert aligninput.length == 4;
		String[] rnaaligninput = WSTester.clustalRNAAlignment.split("\n");
		assert aligninput.length == 5;
		// We do now know the type of the input here so must compare with both
		// references
		boolean isReference = compareLines(input, fastainput);
		if (!isReference) {
			isReference = compareLines(input, aligninput);
		}
		if (!isReference) {
			isReference = compareClustalLines(input, rnaaligninput);
		}
		// only accept genuine input
		return !isReference;
	}

	private static boolean compareLines(File input, String[] reference) {
		BufferedReader reader = null;
		boolean status = true;
		try {
			reader = new BufferedReader(new FileReader(input));
			// only compare first four lines of the file with reference
			// because the reference length is only 4 lines
			for (int i = 0; i < reference.length; i++) {
				String line = reader.readLine();
				if (Util.isEmpty(line)) {
					status = false;
					break;
				}
				line = line.trim();
				if (!line.equals(reference[i].trim())) {
					status = false;
					break;
				}
			}
			reader.close();
		} catch (IOException ioe) {
			log.warn(ioe, ioe.getCause());
		} finally {
			FileUtil.closeSilently(reader);
		}
		return status;
	}

	private static boolean compareClustalLines(File input, String[] reference) {
		BufferedReader reader = null;
		boolean status = true;
		try {
			reader = new BufferedReader(new FileReader(input));
			// only compare first four lines of the file with reference
			// because the reference length is only 4 lines
			int i = 0;
			String line;
			while (null != (line = reader.readLine())) {
				if (!Util.isEmpty(line)) {
					line = line.trim();
					if (!line.equals(reference[i].trim())) {
						status = false;
						break;
					}
					++i;
				}
			}
			reader.close();
		} catch (IOException ioe) {
			log.warn(ioe, ioe.getCause());
		} finally {
			FileUtil.closeSilently(reader);
		}
		return status;
	}
}
