package wto.prito.inf66268.util;

import java.io.*;

public class SheetReader {

	private String configurationString;
		
	/**
	 * Two values to remember current position i 
	 * sheet while genereting
	 */
	private int currentRow;
	private char currentColl;
	
	/**
	 * Two values to remember current position i 
	 * sheet while genereting
	 */
	private int maxRow;
	private char maxColl;
	
	private Sheet sheet;
	

	/**
	 * Reader configuration
	 * 
	 * @param configurationString
	 */
	public SheetReader(String configurationString) {
		this.configurationString = configurationString;
		currentRow = 0;
		currentColl = 'A' - 1;
		sheet = new Sheet();
	}

	/**
	 * metod that read the file and generate sheet
	 * 
	 * @return
	 */
	public Sheet read(){
		BufferedReader input = null;

		try {
			input = new BufferedReader(new FileReader(configurationString));
			String line = null;			

			line = input.readLine();
			while(line != null){
				generateRow(line);
				line = input.readLine();
			}
			
			sheet.setMaxCollAndRow(maxColl, maxRow);

			input.close();
			return sheet;
			
		} catch (IOException e) {
			System.out.println(e.getMessage());
			try {
				if(input != null)
					input.close();
			} catch (IOException er) {
				System.out.println(er.getMessage());
				return null;
			}
			return null;
		}
	}
	
	private void generateRow(String line){
		String regX = "\\|";		
		int numberOfColumns = line.split(regX).length;
				
		currentRow++;
		maxRow = currentRow;
		for(char i = 0;i < numberOfColumns;i++){
			currentColl++;
			if(maxColl < currentColl)
				maxColl = currentColl;
			sheet.addCell(currentRow, currentColl, line.split(regX)[i]);			
		}
		currentColl = 'A' - 1;
	}

}
