package org.ourfilesystem.simpleui;

/*
OurFileSystem is a peer2peer file sharing program.
Copyright (C) 2012  Robert Gass

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

*/

import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;

import javax.swing.table.AbstractTableModel;

import org.ourfilesystem.com.ConnectionUpdateInterface;
import org.ourfilesystem.db.Peer;

public class ConnectionsTable extends AbstractTableModel {
	private static final long serialVersionUID = 1L;

	private String columns[] = {
			"Peer",
			"Location",
			"Introduction",
			"Pending",
			"Signed by"
	};
	
	private HashSet<Peer> Connections;
	private HashMap<Peer, ConnectionUpdateInterface> ConMap;
	
	public ConnectionsTable() {
		Connections = new HashSet<Peer>();
		ConMap = new HashMap<Peer, ConnectionUpdateInterface>();
	}
	
	public synchronized void connectionUpdate(ConnectionUpdateInterface c) {
		Connections.add(c.getPeer());
		ConMap.put(c.getPeer(), c);
		fireTableDataChanged();
	}
	
	public synchronized void removeConnection(Peer p) {
		Connections.remove(p);
		ConMap.remove(p);
		fireTableDataChanged();
	}

	public String getColumnName(int col) {
		return columns[col];
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public Class getColumnClass(int col) {
		if (col == 3) {
			return Integer.class;
		}
		return String.class;
	}
	
	@Override
	public int getColumnCount() {
		return columns.length;
	}

	@Override
	public synchronized int getRowCount() {
		return Connections.size();
	}

	@Override
	public synchronized Object getValueAt(int row, int col) {
		Iterator<Peer> i = Connections.iterator();
		Peer up = null;
		int cnt = 0;
		while (i.hasNext() && cnt <= row) {
			up = i.next();
			cnt++;
		}
		if (up != null) {
			if (col == 0) {
				return up.getNickSig();
			}
			else if (col == 1) {
				return up.getLocation();
			}
			else if (col == 2) {
				return up.getIntroduction();
			}
			else if (col == 3) {
				ConnectionUpdateInterface c = ConMap.get(up);
				if (c != null) {
					return c.getPendingRequests();
				}
				return null;
			}
			else if (col == 4) {
				return up.getPeerKeysAndIdentity().getSignature().getPeerIdentifier().toString().substring(0,10);
			}
		}
		return null;
	}

}
