package Util;

import java.io.*;
import java.util.*;
import javax.swing.*;


public class FileCounter {
    
    private File file;
    private Hashtable stat;
    
    public FileCounter(File f){
	file = f;
	
    }
    
    


    private boolean countFile(){
	
	stat = new Hashtable(); 
	String token = "";
	String str = "";
	int row_count = 0;
	
	    
	InFile infile = null;
	try{
	    infile = new InFile(file.getAbsolutePath());
	}catch(Exception e){	 
	    JOptionPane.showMessageDialog(null,
					  "Can not Read Data Source",
					  "Error",
					  JOptionPane.ERROR_MESSAGE);
	    return false ;
	}
	
	
	
	while(true){
	    try{
		str = infile.readLine();
	    }catch(Exception re){
	    }
	    
	    if(str == null )
		break;
		
	    StringTokenizer st = new StringTokenizer(str);
	    if(!st.hasMoreTokens())
		continue;
	    int col_count = 0;
	    
	    int word_count = 0;
	    while(st.hasMoreTokens()){
		token = st.nextToken();
		word_count++;
	    }
		
		
	    // write to stat hashtable
	    Integer index = new Integer(word_count);
	    if(stat.containsKey(index)){
		Integer obj = (Integer)stat.get(index);
		int objVal = obj.intValue();
		stat.put(index,new Integer(++objVal));
	    }else{
		stat.put(new Integer(word_count), new Integer(1));
	    }
	    
	    row_count++;
	}
	
	return true;
    }
    
    
    public void report(){
	if(stat == null ){
	    if(!countFile())
		return;
	}
	
	String info = file.getName() + "\n\n";
	Enumeration keys = stat.keys();
	while(keys.hasMoreElements()){
	    Integer index = (Integer)keys.nextElement();
	    Integer obj = (Integer)stat.get(index);
	    info += new String(obj + " Lines with " + index + " Columns\n");
	}
	
	JOptionPane.showMessageDialog(null,
				      info,
				      "Structure: Open Data File",
				      JOptionPane.INFORMATION_MESSAGE);
	
	return;
    }

}
