package com.ethon.io;

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

import com.ethon.DataBase;
import com.ethon.mode.DataPoint;
import com.ethon.tools.ErrorHandler;

/**
 * 数据读取器负责数据的读取工作
 * @author ethonchan	ethonchan@gmail.com 
 */
public class DataReader {

	// 从文件中读取第groupNum组数据，groupNum从0开始
	public DataPoint[] getDataPoints(File file, int groupNum) {
		if (groupNum < 0) {
			ErrorHandler.log("groupNum 不能为负");
			return null;
		}
		DataPoint[] points = null;
		DataBase db = DataBase.getInstance();
		try {
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String str = reader.readLine();
			while (str != null) {
				if (str.length() != 0 && !str.startsWith("//")) {
					if (str.startsWith(".new"))
						break;
					DataPoint dp = DataPoint.getNewPoint(str);
					points = db.insertPoint(dp);
				}
				str = reader.readLine();
			}
			int length = 0;
			while (groupNum > -1 && str != null) {
				if (str.length() != 0 && !str.startsWith("//")) {
					if (str.startsWith(".new"))
						groupNum--;
					else {
						points[length % points.length].update(str);
						length++;
					}
					str = reader.readLine();
				}
			}
			reader.close();
			return points;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public int getGroupNum(File file) {
		int len = 1;
		boolean empty = true;
		try {
			@SuppressWarnings("resource")
			BufferedReader reader = new BufferedReader(new FileReader(file));
			String str = reader.readLine();
			while (str != null) {
				if (str.startsWith(".new"))
					len++;
				if (str.length() != 0 && !str.startsWith("//"))
					empty = false;
				str = reader.readLine();
			}
			if (!empty)
				return len;
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return 0;
	}

}
