package View;

import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;

import Controller.Controller;
import Model.Meaning;
import Model.Pair;
import Model.Word;

/**
 * Class to display all the words with all the meanings possibly cresponding to them.
 * @author simon
 *
 */
public class WordTablePanel extends DataPanel {

	MyTableModel myTable;
	
	
	public WordTablePanel(Controller controller) {
		super(controller);	
		
		
		
		Object[][] data= new Object[0][0];
		String[] columns={"Word","Meaning","probability","frequency"};
	
		
		myTable=new MyTableModel(columns,data,false);
		JTable table=new JTable(myTable);
		
		JScrollPane scrollPane = new JScrollPane(table);
		table.setFillsViewportHeight(true);
		
		JPanel container=new JPanel();
		container.setLayout(new BorderLayout());
		
		this.setLayout(new GridBagLayout());
		GridBagConstraints c = new GridBagConstraints();
		c.fill = GridBagConstraints.BOTH;
		c.weightx=1.0;
		c.weighty=1.0;
		
		this.add(scrollPane,c);
	}

	public void updatePanel(){
		
		//find the max table length
		int maxRows=0;
		
		Iterator<Word> it = cont.getWordTableData().iterator();
		while (it.hasNext()){
			Word w = it.next();
			Pair<Integer,HashMap<Meaning,Double>>  pair=w.getLastState();
			if(pair != null)
				maxRows+=pair.getSecond().size();
			
		}
		myTable.emptyResize(maxRows,4);
		
		//order the words 
		
		
		TreeSet<Word> sortedWords=new TreeSet<Word>(cont.getWordTableData());
		it =sortedWords.iterator();		
		int nextRow=0;
		while (it.hasNext()){
			nextRow=setRows(it.next(),nextRow);
		}
	}
	
	//writes the data of one word in the following row
	private int setRows(Word w, int nextRow){
		int freq=w.getFrequency();
		
		// get last iteration the word appeared
		Pair<Integer, HashMap<Meaning, Double>> statePair=w.getLastState();
		if(statePair != null){
			HashMap<Meaning, Double> state=statePair.getSecond();
			
			TreeSet<Meaning> sortedKeys=new TreeSet<Meaning>(state.keySet());
			Iterator<Meaning> it = sortedKeys.iterator();
			while(it.hasNext()){
				Meaning mean=it.next();
				myTable.setRow(new Object[]{w.getStringRep(),mean,state.get(mean),freq}, nextRow);
				nextRow++;
			}
		}
		return nextRow;
	}
}
